简体   繁体   English

为什么JPanel没有显示ImageIcon?

[英]Why isn't the JPanel showing the ImageIcon?

I have a GridBagConstraints gbcImage and a JLabel that is initialized like this: 我有一个GridBagConstraints gbcImage和一个初始化的JLabel ,如下所示:

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 . 将面板添加到JFrame

So I implemented a MouseListener to the label: 所以我在标签上实现了一个MouseListener

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? 我错过了什么?

There is no need to create a new JLabel. 无需创建新的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. 问题是您向面板添加了一个新标签,但其默认大小为(0,0),因为您没有reavalidate()repaint()面板。

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 );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM