Page 1 of 2 12 LastLast
Results 1 to 20 of 23
Like Tree1Likes

Thread: How to add an ImageIcon on a JPanel???

  1. #1
    Angelo is offline Member
    Join Date
    Dec 2011
    Posts
    24
    Rep Power
    0

    Post How to add an ImageIcon on a JPanel???

    Hi guys, I'm trying to add some icons on a JPanel an I obviously have some problems... My purpose is to add some little .jpg images on a JPanel with his own background. Here is the code of my function:

    Java Code:
     import javax.swing.*;
    import java.awt.*;
    .................................
    .................................
    public void addPlayer (Player p) {
            final int xCoord = p.xPosition;
            final int yCoord = p.yPosition;
            final String playerIconPath = p.iconPath; 
            JTextArea infoPlayer = new JTextArea();
            infoPlayer.setFont(font);
            infoPlayer.setForeground(Color.yellow);
            infoPlayer.setBounds(p.xPosition, p.yPosition,65,30);
            infoPlayer.setText(p.getName() + "\n" + p.stack + "€");
            infoPlayer.setBackground(Color.BLACK);
            infoPlayer.setEditable(false);
            if (p.hasIcon) {
                JComponent playerAvatar = new JComponent() {
                    protected void paintComponent(Graphics g) {
                        final ImageIcon playerIcon = new ImageIcon (playerIconPath);
                        setOpaque(false);
                        g.drawImage(playerIcon.getImage(),xCoord,yCoord+d.height, d.width, d.height, frame.getContentPane());
                        super.paintComponent(g);
                    }
                };
    room.add(playerAvatar);
        }
    room.add(infoPlayer);
    }
    ......................................................
    ......................................................
     room = new JPanel() {
                protected void paintComponent (Graphics g) {
                    setOpaque(false);
                    Dimension s = getSize();
                    try {
                        g.drawImage(backgroundIcon.getImage(),0,0,s.width,s.height,null);
                    }
                    catch (NullPointerException ex) {
                        System.out.println("File not found");
                    }
                    super.paintComponent(g);
                }
            };
    frame.add(room);
    ..............................................
    ..............................................
    Now what I get is that the compiler finds no errors, but when I execute the program I can see everything but the little icons....

    Does someone can suggest anything? I also tried with some System.out.println methods to see if the variables are ok and they are...

  2. #2
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,814
    Rep Power
    25

    Default Re: How to add an ImageIcon on a JPanel???

    One obvious error is the call to super.paintComponent(g);
    after your drawing. That call clears the drawing.
    Move it to be done first thing in the method.

  3. #3
    Angelo is offline Member
    Join Date
    Dec 2011
    Posts
    24
    Rep Power
    0

    Default Re: How to add an ImageIcon on a JPanel???

    Thanks, I tried as you said but it still doesn't work. Actually I've inserted this code in that method:
    Java Code:
    JComponent playerAvatar = new JComponent() {                
                    protected void paintComponent(Graphics g) {
                        super.paintComponent(g);
                        System.out.println(playerIconPath);
                        final ImageIcon playerIcon = new ImageIcon (playerIconPath);
                        setOpaque(false);
                        try {
                            g.drawImage(playerIcon.getImage(),xCoord,yCoord+30, xCoord+30, yCoord, null);
                        }
                        catch (NullPointerException exc) {
                            System.out.println("Error: icon not found");
                        }
                    }
                };
                room.add(playerAvatar);
    I expected to have some kind of output on my prompt (line 4) but I have nothing at all. It looks like the method paintComponent is never called but I don't know why...

  4. #4
    Angelo is offline Member
    Join Date
    Dec 2011
    Posts
    24
    Rep Power
    0

    Default Re: How to add an ImageIcon on a JPanel???

    Moreover when I call the same method for the JPanel it works fine even with the super.paintComponent called at the end of the method.

  5. #5
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,814
    Rep Power
    25

    Default Re: How to add an ImageIcon on a JPanel???

    Just tried using a JComponent vs a JPanel and it does display a GUI.
    LaL
    Last edited by Norm; 12-18-2011 at 05:31 PM.

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

    Default Re: How to add an ImageIcon on a JPanel???

    It's hard (for me) to see what you're doing wrong, and I suspect that it may be in code not shown. Perhaps you're not revalidating and repainting the container which is receiving the new component after adding the component, perhaps the new component's size is 0,... for me it's hard to say based on the code snippets.

    If you're still stuck, I suggest that you create a small compilable and runnable program that demonstrates your problem, that tries to add some images to a GUI perhaps after the GUI has been rendered, if that's your goal, and that we can compile and run on our own. If you do this, it would be best for you to use images that we can get online (I often use images obtained here) and adhere as best you can to the rules of a well-behaved SSCCE.

  7. #7
    Angelo is offline Member
    Join Date
    Dec 2011
    Posts
    24
    Rep Power
    0

    Default Re: How to add an ImageIcon on a JPanel???

    ok I'll try to create a simple program. Meanwhile can you please explain me how should I repaint the panel? Why every component is added correctly (e.g. the infoPlayer JTextArea) while the playerAvatar JComponent not? And why do you think it does not print the image path when I call the System.out.println method? Maybe I should call this Jcomponent differently from a default JComponent?

  8. #8
    Angelo is offline Member
    Join Date
    Dec 2011
    Posts
    24
    Rep Power
    0

    Default Re: How to add an ImageIcon on a JPanel???

    Norm what do you mean? Should I create a GUI component like a rectangle and THEN paint it?

  9. #9
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,814
    Rep Power
    25

    Default Re: How to add an ImageIcon on a JPanel???

    I think a SSCCE is needed to show what your problem is. A JComponent vs JPanel worked for me.
    One comment: You should not be reading the image file inside of the paint method, unless it changes everytime the method is called.
    Fubarable likes this.

  10. #10
    Angelo is offline Member
    Join Date
    Dec 2011
    Posts
    24
    Rep Power
    0

    Default Re: How to add an ImageIcon on a JPanel???

    Ehm... can you please explain what SSCCE stands for?

  11. #11
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,814
    Rep Power
    25

    Default Re: How to add an ImageIcon on a JPanel???

    See the link at the end of post#6.

  12. #12
    Angelo is offline Member
    Join Date
    Dec 2011
    Posts
    24
    Rep Power
    0

    Default Re: How to add an ImageIcon on a JPanel???

    And how can I load an IconImage from an URL? Should I just put a string with the complete URL as argument of ImageIcon()?

  13. #13
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,814
    Rep Power
    25

    Default Re: How to add an ImageIcon on a JPanel???

    Have you done a Search on the forum for code samples? I'm sure there is lots of sample code.

    If you are getting errors, copy and paste the code and the full text of the error messages.

  14. #14
    Angelo is offline Member
    Join Date
    Dec 2011
    Posts
    24
    Rep Power
    0

    Default Re: How to add an ImageIcon on a JPanel???

    No I'm not getting errors... I can compile the program without any problem. It should be something that doesn't work in the logic of my program.

  15. #15
    Angelo is offline Member
    Join Date
    Dec 2011
    Posts
    24
    Rep Power
    0

    Default Re: How to add an ImageIcon on a JPanel???

    Ok here is a SSCCE... :
    Java Code:
    import java.awt.*;
    import javax.swing.*;
    
    public class MainPanel {
        JFrame frame = new JFrame("Example");
        String pathPanelBackground = "c:\\users\\deliana\\desktop\\tavolo.jpg";
        String pathIconBackground = "c:\\users\\deliana\\desktop\\rihanna.jpg";
        
        JComponent playerAvatar = new JComponent() {
                    final ImageIcon playerIcon = new ImageIcon (pathIconBackground);
                    protected void paintComponent(Graphics g) {
                        super.paintComponent(g);
                        System.out.println(pathIconBackground);
                        setOpaque(false);
                        try {
                            g.drawImage(playerIcon.getImage(),200,200+30, 200+30, 200, null);
                        }
                        catch (NullPointerException exc) {
                            System.out.println("Errore in stampa icona giocatore");
                        }
                    }
                };
    
        JPanel panel = new JPanel() {
            final ImageIcon panelBackground = new ImageIcon(pathPanelBackground);
            protected void paintComponent (Graphics g) {
                setOpaque(false);
                Dimension s = getSize();
                try {
                    g.drawImage(panelBackground.getImage(),0,0,s.width,s.height,null);
                }
                catch (NullPointerException ex) {
                    System.out.println("File not found");
                }
                super.paintComponent(g);
            }
        };
        public void loadPanel() {
            panel.setLayout(null);
            panel.add(playerAvatar);
            frame.add(panel);
            frame.setSize(600,600);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setVisible(true);
        }
        
        public static void main(String [] args) {
            MainPanel mainPanel = new MainPanel();
            mainPanel.loadPanel();
        }
    }
    You shold just change the images path in the inital declaration.

  16. #16
    Angelo is offline Member
    Join Date
    Dec 2011
    Posts
    24
    Rep Power
    0

    Default Re: How to add an ImageIcon on a JPanel???

    i'm getting mad... now I commented line 39: panel.setLayout(null) and the image did not appear but... I had the path printed on my prompt...

  17. #17
    Angelo is offline Member
    Join Date
    Dec 2011
    Posts
    24
    Rep Power
    0

    Default Re: How to add an ImageIcon on a JPanel???

    news over news... everytime i resize the window with the mouse i have the path printed!!! so this means that the program is calling that function but the image just does not appear....

  18. #18
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,814
    Rep Power
    25

    Default Re: How to add an ImageIcon on a JPanel???

    What is supposed when the above program is executed? I get a window with the pathPanelBackground image showing. Nothing prints on the console.

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

    Default Re: How to add an ImageIcon on a JPanel???

    Your SSCCE again should use available images. For e.g.,

    Java Code:
    import java.awt.*;
    import java.awt.image.BufferedImage;
    import java.io.IOException;
    import java.net.MalformedURLException;
    import java.net.URL;
    
    import javax.imageio.ImageIO;
    import javax.swing.*;
     
    public class MainPanel {
        JFrame frame = new JFrame("Example");
        String pathPanelBackground = "http://duke.kenai.com/glassfish/" +
              "GlassFishMedium.jpg";
        String pathIconBackground = "http://duke.kenai.com/iconSized/duke.gif";
        private ImageIcon playerIcon = null;
        private ImageIcon panelBackground = null;
         
        JComponent playerAvatar = new JComponent() {
                    protected void paintComponent(Graphics g) {
                        super.paintComponent(g);
                        System.out.println(pathIconBackground);
                        setOpaque(false);
                        if (playerIcon != null) {
                           g.drawImage(playerIcon.getImage(),200,200+30, 200+30, 200, null);
                      }
                    }
                };
     
        JPanel panel = new JPanel() {
            protected void paintComponent (Graphics g) {
               super.paintComponent(g);
                Dimension s = getSize();
                if (panelBackground != null) {
                   g.drawImage(panelBackground.getImage(),0,0,s.width,s.height,null);
                }
            }
        };
        public void loadPanel() {
           try {
             BufferedImage playerImg = ImageIO.read(new URL(pathIconBackground));
             BufferedImage backgroundImg = ImageIO.read(new URL(pathPanelBackground));
             playerIcon = new ImageIcon(playerImg);
             panelBackground = new ImageIcon(backgroundImg);
             // panel.setLayout(null);
             panel.add(playerAvatar);
             frame.add(panel);
             frame.setSize(600,600);
             frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             frame.setVisible(true);
             
             System.out.println("playerAvatar size: " + playerAvatar.getSize());
          } catch (MalformedURLException e) {
             e.printStackTrace();
          } catch (IOException e) {
             e.printStackTrace();
          }
           
        }
         
        public static void main(String [] args) {
            MainPanel mainPanel = new MainPanel();
            mainPanel.loadPanel();
        }
    }
    Note that I also added a line of code to show the size of the playerAvatar after the GUI has been rendered. You'll see that it's quite small, [1, 1] -- too small to render anything of use, and that's your main problem here. Also, don't use a try/catch for a NPE. Instead use an if block as I show above.

    Why not simply put an ImageIcon into a JLabel and display it? For e.g.,

    Java Code:
    import java.awt.*;
    import java.awt.image.BufferedImage;
    import java.io.IOException;
    import java.net.MalformedURLException;
    import java.net.URL;
    
    import javax.imageio.ImageIO;
    import javax.swing.*;
    
    public class MainPanel2 {
       private static final String PATH_ICON_URL = "http://duke.kenai.com/iconSized/duke.gif";
       private static final String PATH_BACKGROUND_URL = "http://duke.kenai.com/glassfish/" +
       		"GlassFishMedium.jpg";
       private JFrame frame = new JFrame("Example");
       private BufferedImage backgroundImage = null;
    
       JPanel panel = new JPanel() {
          protected void paintComponent(Graphics g) {
             super.paintComponent(g);
             Dimension s = getSize();
             if (backgroundImage != null) {
                g.drawImage(backgroundImage, 0, 0, s.width, s.height,
                      null);
             }
          }
       };
    
       public void loadPanel() {
          try {
             URL backgroundUrl = new URL(PATH_BACKGROUND_URL);
             URL iconUrl = new URL(PATH_ICON_URL);
             BufferedImage iconImage = ImageIO.read(iconUrl);
             backgroundImage = ImageIO.read(backgroundUrl);
             Icon icon = new ImageIcon(iconImage );  
             JLabel playerAvatar = new JLabel(icon);
             playerAvatar.setBorder(BorderFactory.createTitledBorder("Avatar"));
             panel.add(playerAvatar);
             frame.add(panel);
             frame.setSize(600, 600);
             frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             frame.setVisible(true);
          } catch (MalformedURLException e) {
             e.printStackTrace();
          } catch (IOException e) {
             e.printStackTrace();
          }
       }
    
       public static void main(String[] args) {
          MainPanel2 mainPanel = new MainPanel2();
          mainPanel.loadPanel();
       }
    }

  20. #20
    Angelo is offline Member
    Join Date
    Dec 2011
    Posts
    24
    Rep Power
    0

    Default Re: How to add an ImageIcon on a JPanel???

    so basically you
    1. defined the playerAvatar as a JLabel;
    2. did not set the panel layout as null, so you used the flowlayout;

    so I can not use a generic JComponent, but I have to define the avatar as a JLabel right?

    why if I set the layout = null the image does not appear?

Page 1 of 2 12 LastLast

Similar Threads

  1. JFrame+JPanel+JButton+JtextArea+ImageIcon
    By zusss in forum AWT / Swing
    Replies: 11
    Last Post: 02-18-2011, 11:40 AM
  2. Need help with ImageIcon and int
    By proceeded in forum New To Java
    Replies: 9
    Last Post: 01-23-2011, 11:10 PM
  3. ImageIcon HELP!
    By ben1989 in forum New To Java
    Replies: 1
    Last Post: 05-05-2010, 09:48 PM
  4. send imageIcon over RMI
    By nadia in forum Advanced Java
    Replies: 4
    Last Post: 01-06-2009, 04:41 PM
  5. ImageIcon and size
    By wokena in forum Java 2D
    Replies: 3
    Last Post: 12-21-2008, 09:47 AM

Tags for this Thread

Posting Permissions

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