点击按钮,在JPanel中加载图像

时间:2014-05-13 12:59:14

标签: java swing jframe jpanel

我已经看到很多关于此的答案,但似乎没有解决我的问题,我在选项卡式窗格(相同的选项卡)中有一个jPanel1和jPanel3,当我从jPanel1点击一个按钮然后我去jPanel3中加载一个图像。 以下是我尝试做同样的事情

jButton1.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

            System.out.println("In the action");
            try {
                jPanel3.add(new JPanel(){
                    java.net.URL imgURL = this.getClass().getResource( "/resource/images/cd-dvd-icon.png");
                    BufferedImage image = ImageIO.read(imgURL);
                });
                jPanel3.revalidate();
                jPanel3.repaint();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    });

但我没有看到任何错误或图像。请帮忙

2 个答案:

答案 0 :(得分:4)

您没有将图像添加到面板。使用里面的图像创建一个JLabel,然后将标签添加到jPanel3:

        try 
        {
            JLabel imgLabel = new JLabel(new ImageIcon(this.getClass().getResource( "/resource/images/cd-dvd-icon.png")));
            jPanel3.add(imgLabel);
            jPanel3.revalidate();
            jPanel3.repaint();
        }catch (Exception ex){
            ex.printStackTrace();
        }

答案 1 :(得分:0)

最后想出了问题,再次添加了布局,就像它在生成的代码中添加一样,并且工作正常

jButton3.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
           System.out.println("In the action");
           JLabel imgLabel = new JLabel(new ImageIcon(this.getClass().getResource( "/resource/images/cd-dvd-icon.png")));
            jPanel2.add(imgLabel);
            jPanel2.revalidate();
            jPanel2.repaint();
            jPanel2.setLayout(jPanel2Layout);
            jPanel2Layout.setHorizontalGroup(
                jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel2Layout.createSequentialGroup()
                    .addGap(24, 24, 24)
                    .addComponent(jButton3)
                    .addGap(59, 59, 59)
                    .addComponent(jToggleButton1)
                    .addGap(50, 50, 50)
                    .addComponent(imgLabel)
                    .addContainerGap(235, Short.MAX_VALUE))
            );
            jPanel2Layout.setVerticalGroup(
                jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel2Layout.createSequentialGroup()
                    .addGap(33, 33, 33)
                    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jToggleButton1)
                        .addComponent(jButton3))
                        .addGap(59, 59, 59)
                        .addComponent(imgLabel)
                    .addContainerGap(368, Short.MAX_VALUE))
            );
        }

    });