通过单击JButton在JPanel上显示图像

问题描述

我刚刚开始学习GUI编程,并且在加载图像时遇到了问题。 我想在BorderLayout的WEST上放置一个JButton,并通过单击该JButton在CENTER中显示图像。

请参考这张图片:

Please refer to this picture

代码如下所示。我已经尝试了几个小时,但还是没能做到。

public class Testing extends JFrame {
    private JButton btn;
    private JLabel pict;
    private JPanel wpanel,cpanel;
    private BufferedImage image;
    
    Testing(){
        Container cont = getContentPane();
        setLayout(new BorderLayout());
        
        //add button
        wpanel = new JPanel();
        cpanel = new JPanel();
        btn = new JButton("Click me");
        wpanel.add(btn);
        
        
        //Clicking button to load image
            //inner class
        btn.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent evt){
                try {
                    loadImage();

                    SwingUtilities.invokeLater(new Runnable(){
                        @Override
                        public void run() {
                            createAndShowGUI();             
                        }
                    });
                } catch (IOException e) {
                    System.out.println("Couldn't load image.");
                }
            }
        });


        public void loadImage() throws IOException{
            image = ImageIO.read(Testing.class.getResource("/path/.jpg"));
        }

        public void createAndShowGUI(){
            pict = new JLabel();
            pict.setIcon(new ImageIcon(image));
            cpanel.add(pict);
        }
        //end of clicking button to load image
        
        cont.add(wpanel,BorderLayout.WEST);
        cont.add(cpanel,BorderLayout.CENTER);
    
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setTitle("JFrame"); 
        setSize(300,300);  
        setVisible(true); 
    }
    
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
         @Override
         public void run() {
            new Testing();  
         }
         
        });
   }

}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...