1

I have a GridBagConstraints gbcImage and a JLabel that is initialized like this:

gbcImage.gridx = 1; // column 0
gbcImage.gridy = 2; // row 2
gbcImage.ipady = 100;
gbcImage.ipadx = 100;
JLabel label = new JLabel("", null, JLabel.CENTER);
label.setOpaque(true);
label.setBackground(Color.WHITE);
panel.add(label, gbcImage);

Where panel is added to a JFrame.

So I implemented a MouseListener to the label:

public void mouseClicked(MouseEvent e) {
            JFileChooser jfc = new JFileChooser();

            int iRet = jfc.showOpenDialog(panel);
            if (iRet == jfc.APPROVE_OPTION)
            {
                File file = jfc.getSelectedFile();

                try 
                {
                    BufferedImage bi = ImageIO.read(file);
                    image = new ImageIcon(bi);
                    JLabel label = new JLabel("", image, JLabel.CENTER);
                    panel.add(label, gbcImage);
                } 
                catch (IOException e1) 
                {
                    e1.printStackTrace();
                }
            }
        }

But it didn't work. The image doesn't show in the panel at runtime.

What am I missing?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • have you specified the LayoutManager for your JPanel? – ACV Aug 26 '16 at 21:34
  • 1) For better help sooner, post a [MCVE] or [Short, Self Contained, Correct Example](http://www.sscce.org/). 2) One way to get image(s) for an example is to hot link to images seen in [this Q&A](http://stackoverflow.com/q/19209650/418556). – Andrew Thompson Aug 27 '16 at 01:30

1 Answers1

3

There is no need to create a new JLabel. The problem is you added a new label to the panel but its default size is (0, 0) because you didn't reavalidate() and repaint() the panel.

There is no need to create a new label.

Instead you keep a reference to the original label (like you do for the panel) and then you just replace the icon:

image = new ImageIcon(bi);
label.setIcon( image );
Arthur
  • 1,246
  • 1
  • 15
  • 19
camickr
  • 321,443
  • 19
  • 166
  • 288