Results 1 to 19 of 19
  1. #1
    vaggos is offline Member
    Join Date
    Aug 2012
    Posts
    12
    Rep Power
    0

    Default Background image in jframe

    Hello everyone.

    I am desperately trying to set a background image in a jframe I have created.I have seen many links via the internet but I cannot fully understand how to procceed.
    The problem is that along with the jframe,I created 2 panels that must be attached to it because the first panel is for image display and the second panel is for adding and removing images in/from the first panel.I have set Layouts to those panels so that they appear the way I want them to.Is there any way to add background image with minor code changes?My code is around 1200 lines and it would be a little bit hard to change everything(I have added many buttons and some other stuff in panel No2).I have checked layered panes but none of my efforts produced results.

    Thank you.

  2. #2
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,390
    Rep Power
    25

    Default Re: Background image in jframe

    Try to make a small program that compiles, executes and shows the problem.
    Without the code you are having problems with it is hard to know what to recommend.
    If you don't understand my response, don't ignore it, ask a question.

  3. #3
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default Re: Background image in jframe

    Quote Originally Posted by vaggos View Post
    Hello everyone.

    I am desperately trying to set a background image in a jframe I have created.I have seen many links via the internet but I cannot fully understand how to procceed.
    The problem is that along with the jframe,I created 2 panels that must be attached to it because the first panel is for image display and the second panel is for adding and removing images in/from the first panel.I have set Layouts to those panels so that they appear the way I want them to.Is there any way to add background image with minor code changes?My code is around 1200 lines and it would be a little bit hard to change everything(I have added many buttons and some other stuff in panel No2).I have checked layered panes but none of my efforts produced results.

    Thank you.
    Hopefully that 1200 lines of code is well refactored into classes such that each class isn't too big. If you've done that well, it's usually not too difficult to modify things so that your background image will be easy to implement. But I agree with Norm that without knowing more, it will be hard to give you any specific recommendations.

  4. #4
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default Re: Background image in jframe

    Also, to motivate folks to help you more, consider replying to posts made as no one likes to think that their advice is being ignored. I'm referring to your previous thread in this forum where it appears that you received some excellent advice.

  5. #5
    vaggos is offline Member
    Join Date
    Aug 2012
    Posts
    12
    Rep Power
    0

    Default Re: Background image in jframe

    sorry about that,I saw the reply from another pc where I was not logged in and two days ago that I returned in my house,I totally forgot it!
    I will answer to that post and also I will try to write here a short piece of code to demonstrate my problem!

  6. #6
    vaggos is offline Member
    Join Date
    Aug 2012
    Posts
    12
    Rep Power
    0

    Default Re: Background image in jframe

    Background image in jframe-viewer.jpg

    I hope the image is attached well...
    Panel No 2 is the panel 'Actions' shown in the image.
    Above panel2,there is panel1 which displays the selected images.
    Note that panel 2 is also subdivided in other panels,one that holds the buttons on the left of "My selected images",one on the right of it,and a third that is the "My selected images" itself.All using GridLayout to display the components.
    These 2 panels are added in my jframe.some example code is the following:

    Java Code:
    final JPanel panel1 = new JPanel();
    panel1.setPreferredSize(new Dimension(650,470));
         
    final  JPanel panel2 = new JPanel(new GridLayout(0,3));
    panel2.setBorder(BorderFactory.createTitledBorder(null,"Actions",
                    javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION,
                    javax.swing.border.TitledBorder.DEFAULT_POSITION,
                    new Font("Tahoma", 1, 10),
                    new Color(0,0,0)));
    panel2.setPreferredSize(new Dimension(250,170));
    ....
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //frame.setResizable(false);
            frame.setLocation(0, 0);
            frame.setPreferredSize(new Dimension(1000,705));
            frame.setLayout(new BorderLayout());
            frame.pack();
            frame.setVisible(true);
            frame.add(panel1,BorderLayout.CENTER);
            frame.add(panel2,BorderLayout.SOUTH);
    My goal is to add a "Set Background Image" button which will function as follows:
    1)The user chooses an image file of his choice
    2)That image is set as a background.

    That means that all components(panel1,panel2 etc)must be "independent" from the frame.I thought the best solution would be to create a layered pane but I don't know how,despite all my research.I know how to display images etc,but of course when I try to display the background image,it simply fills the gap between panel1 and panel2
    I have also created the following class to help me draw the bground image
    Java Code:
    class bground extends JPanel{
        Image img;
        bground()
        {
            ImageIcon icon = new ImageIcon("C:\\Castle.jpg");
            img = icon.getImage();
        }
        
        public void paint(Graphics g)
        {
            
            g.drawImage(img,0,0,getSize().width,getSize().height,this);
            setOpaque(false);
            super.paint(g);
            setOpaque(true);
        }
        
    }

  7. #7
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,234
    Rep Power
    19

    Default Re: Background image in jframe

    1. Go through this Tutorial Lesson: Performing Custom Painting (The Java™ Tutorials > Creating a GUI With JFC/Swing) where you will learn the correct method to override for custom painting in Swing. Hint: it's not paint(...)

    2. Never change state of a component in any painting method override. What are you trying to achieve with calls to setOpaque(...) anyways?

    3. super.paint(g) performs the default painting, which calls the three Swing methods that actually do the painting. One of them clears the background -- including any image you may have already drawn.

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  8. #8
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,390
    Rep Power
    25

    Default Re: Background image in jframe

    Do you have a small program that will compile, execute and show the problem? Hard to test bits of code.
    If you don't understand my response, don't ignore it, ask a question.

  9. #9
    vaggos is offline Member
    Join Date
    Aug 2012
    Posts
    12
    Rep Power
    0

    Default Re: Background image in jframe

    I will try to fix a small program and post it :)

    @darrylburke I will check your link.unfortunately I have not understood all this "painting" procedure very well and that class was my first effort to use paint().Since it worked I left it behind but I will check it again because I am stuck with this problem.

  10. #10
    vaggos is offline Member
    Join Date
    Aug 2012
    Posts
    12
    Rep Power
    0

    Default Re: Background image in jframe

    Java Code:
    package back;
    import javax.swing.*;
    
    import javax.swing.JPanel;
    import java.awt.*;
    import java.awt.Graphics;
    
    
    class bground extends JPanel{
        Image img;
        bground()
        {
            ImageIcon icon = new ImageIcon("C:\\Castle.jpg");
            img = icon.getImage();
        }
        
        public void paint(Graphics g)
        {
            
            g.drawImage(img,0,0,getSize().width,getSize().height,this);
            setOpaque(false);
            super.paint(g);
            setOpaque(true);
        }
        
    }
    public class Main {
      final static JFrame frame = new JFrame("Photo Viewer");
      private static void PhotoViewerPanel()
        {
            final JPanel panel1 = new JPanel();
            panel1.setPreferredSize(new Dimension(650,470));
    
            final  JPanel panel2 = new JPanel(new GridLayout(0,3));
            panel2.setBorder(BorderFactory.createTitledBorder(null,"Actions",
                    javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION,
                    javax.swing.border.TitledBorder.DEFAULT_POSITION,
                    new Font("Tahoma", 1, 10),
                    new Color(0,0,0)));
            panel2.setPreferredSize(new Dimension(250,170));
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setResizable(false);
            frame.setLocation(0, 0);
            frame.setPreferredSize(new Dimension(1000,705));
            frame.setLayout(new BorderLayout());
            bground back = new bground();
            frame.add(back);
            //frame.add(panel1,BorderLayout.CENTER);
            //frame.add(panel2,BorderLayout.SOUTH);
            frame.pack();
            frame.setVisible(true);
            
        }
    
      public static void main(String[] argv) throws Exception 
        {
            javax.swing.SwingUtilities.invokeLater(new Runnable()
            {
                public void run()
                {
                    PhotoViewerPanel();
                }
            });
        }
    }
    That code seems to work.I mean it displays the image on the jframe.
    Of course,when I uncomment the lines
    //frame.add(panel1,BorderLayout.CENTER);
    //frame.add(panel2,BorderLayout.SOUTH);

    the image disappears(is hidden behind the two panels.when I uncomment one of the two lines,the image appears in the uncovered area )
    At that point I would like to set the image as background.That is,the two panels should be set above the image along with their other components which will function properly and without being affected by background image changes...
    I know I could add each button separately,but that would change a big part of the source code.If there is no other way I may do it eventually...
    Last edited by vaggos; 09-02-2012 at 10:32 PM. Reason: additional info

  11. #11
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default Re: Background image in jframe

    I second Darryl's recommendations: you're still using paint and the tutorials specifically tell you to do otherwise, to use paintComponent, you're still calling setOpaque within paint -- a strange and incorrect thing to do. You're calling the super in the wrong place,...

    Again, you should read the tutorials. Please.

    Next, to add see-through-able JPanels on another JPanel, make sure the ones that you want to see through have their opaque property set to false, and please don't do this from within the paint or paintComponent methods.
    Last edited by Fubarable; 09-02-2012 at 11:07 PM.

  12. #12
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default Re: Background image in jframe

    For example:
    • Adding the BackgroundPanel to the JFrame's contentPane BorderLayout.CENTER,
    • Making the BackgroundPanel use BorderLayout
    • Making panel1 and panel2 non-opaque
    • Drawing in the correct method
    • Calling the super paintComponent method in the right place


    Java Code:
    import javax.imageio.ImageIO;
    import javax.swing.*;
    
    import javax.swing.JPanel;
    import java.awt.*;
    import java.io.IOException;
    import java.net.MalformedURLException;
    import java.net.URL;
    
    class BackgroundPanel extends JPanel {
       public static final String DUKE_GUITAR = "http://duke.kenai.com/guitar/"
             + "DukeAsKeith-daylightSmall.png";
       Image img;
    
       BackgroundPanel() {
          try {
             URL dukeUrl = new URL(DUKE_GUITAR);
             img = ImageIO.read(dukeUrl);
          } catch (MalformedURLException e) {
             e.printStackTrace();
          } catch (IOException e) {
             e.printStackTrace();
          }
       }
    
       @Override
       protected void paintComponent(Graphics g) {
          super.paintComponent(g);
          if (img != null) {
             g.drawImage(img, 0, 0, getSize().width, getSize().height, this);
          }
       }
    
       @Override
       public Dimension getPreferredSize() {
          if (img != null) {
             int imgW = img.getWidth(this);
             int imgH = img.getHeight(this);
             return new Dimension(imgW, imgH);
          }
          return super.getPreferredSize();
       }
    
       final static JFrame frame = new JFrame("Photo Viewer");
    
       private static void PhotoViewerPanel() {
          final JPanel panel1 = new JPanel();
          panel1.setPreferredSize(new Dimension(650, 470));
    
          final JPanel panel2 = new JPanel(new GridLayout(0, 3));
          panel2.setBorder(BorderFactory.createTitledBorder(null, "Actions",
                javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION,
                javax.swing.border.TitledBorder.DEFAULT_POSITION, new Font(
                      "Tahoma", 1, 10), new Color(0, 0, 0)));
          panel2.setPreferredSize(new Dimension(250, 170));
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          BackgroundPanel back = new BackgroundPanel();
          frame.add(back, BorderLayout.CENTER);
          
          panel1.setOpaque(false);  // !!!!
          panel2.setOpaque(false);  // !!!!
          back.setLayout(new BorderLayout());  // !!!!
          back.add(panel1, BorderLayout.CENTER);  // !!!!
          back.add(panel2, BorderLayout.SOUTH);  // !!!!
          
          frame.pack();
          frame.setVisible(true);
    
       }
    
       public static void main(String[] argv) throws Exception {
          javax.swing.SwingUtilities.invokeLater(new Runnable() {
             public void run() {
                PhotoViewerPanel();
             }
          });
       }
    }

  13. #13
    vaggos is offline Member
    Join Date
    Aug 2012
    Posts
    12
    Rep Power
    0

    Default Re: Background image in jframe

    great thank you very much I will
    1)read carefully all about painting to understand differences between paint() and paintComponent() and things like opaque
    2)read your code carefully and test it!

    I will keep you informed for my progress :) thank you all!

  14. #14
    vaggos is offline Member
    Join Date
    Aug 2012
    Posts
    12
    Rep Power
    0

    Default Re: Background image in jframe

    fubarable your code works great!I made a few changes in the rest of the code and works like a charm!!!I will study swing painting to fully understand some things but you have helped me big time!!!thanks!

  15. #15
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default Re: Background image in jframe

    You're welcome, but I probably gave you too much. Again, please read the tutorials as linked by Darryl as you need more than just the code -- you need the concepts.

  16. #16
    vaggos is offline Member
    Join Date
    Aug 2012
    Posts
    12
    Rep Power
    0

    Default Re: Background image in jframe

    Of course I will, because I want to do it on my own so after understanding the procedures,I will make further changes.I already changed some things like creating a separate background class which asks from the user to choose a background image of his choice any time he wants, through file chooser.below is the separate background.java file.

    Java Code:
    package photov;
    
    import javax.imageio.ImageIO;
    import javax.swing.*;
    import javax.swing.JPanel;
    import java.awt.*;
    import java.io.IOException;
    public class Background extends JPanel {
      
       Image img;
    
       Background(String path) {
          ImageIcon icon = new ImageIcon(path);
          img = icon.getImage();
       }
    
       @Override
       protected void paintComponent(Graphics g) {
          super.paintComponent(g);
          if (img != null) {
             g.drawImage(img, 0, 0, getSize().width, getSize().height, this);
          }
       }
    
       @Override
       public Dimension getPreferredSize() {
          if (img != null) {
             int imgW = img.getWidth(this);
             int imgH = img.getHeight(this);
             return new Dimension(imgW, imgH);
          }
          return super.getPreferredSize();
       }
     
    }
    I will study the swing painting and understand it :) I thought it would be much more difficult but after all it's simple if you know what you are doing...

  17. #17
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default Re: Background image in jframe

    Quote Originally Posted by vaggos View Post
    I will study the swing painting and understand it :) I thought it would be much more difficult but after all it's simple if you know what you are doing...
    Some things are simple, but there's much that I don't find it simple at all.

  18. #18
    vaggos is offline Member
    Join Date
    Aug 2012
    Posts
    12
    Rep Power
    0

    Default Re: Background image in jframe

    Sure.But when you learn one thing,then it is easier to implement a few things more.That is how I work at least,step by step.that background problem is torturing me for several days,and turned out that it existed because I did not understand some basic painting principles.So now I can study and understand that too...Before building that jframe I knew almost nothing about java,but after 3 weeks of intense studying I must admit I have made good progress...It was the first time that I used another's source code and I intend to change it too :)

  19. #19
    vaggos is offline Member
    Join Date
    Aug 2012
    Posts
    12
    Rep Power
    0

    Default Re: Background image in jframe

    Hello! I noticed the following problem

    For some reason, .bmp images cannot appear on background.They are loaded ok,they are added ok on my jpanel,but they cannot appear on background when I choose one...Any speculation why that happens?

Similar Threads

  1. set Background image in JFrame
    By redtag in forum AWT / Swing
    Replies: 1
    Last Post: 01-06-2012, 11:01 PM
  2. background image in jframe
    By pardhu in forum AWT / Swing
    Replies: 1
    Last Post: 11-08-2011, 04:00 AM
  3. JFrame image background
    By 851marc in forum NetBeans
    Replies: 5
    Last Post: 03-09-2010, 06:27 PM
  4. How to add a background image to JFrame
    By dunafrothint in forum AWT / Swing
    Replies: 1
    Last Post: 02-26-2010, 10:17 PM
  5. Need help with JFrame background image
    By ProGenius in forum New To Java
    Replies: 6
    Last Post: 12-27-2009, 04:17 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •