image loading using a JFileChooser into a JFrame

孤者浪人 提交于 2019-12-06 01:58:38

The value of img will only have a real value after the user click the button and chooses the file to display. Until this time, the value of img is null, so when it continues through your method and calls the line ImageIcon icon=new ImageIcon(img);, it is trying to create an ImageIcon object for null.

To correct this, you should only be creating the ImageIcon when the user has chosen the file. Here is a change that should be closer to working correctly. (see the comments //ADDED and //REMOVED in the code below to see the changes...

...
class power extends JFrame {
    JFileChooser chooser;
    BufferedImage img;
    JButton button,button2;
    JFrame comp;
    String filename;
    File file ; 
    JLabel label; // ADDED

    public power() {
    ...
            public void actionPerformed(ActionEvent e) {
                if (e.getSource()==button) {
                    chooser.showOpenDialog(null);
                    file = chooser.getSelectedFile();

                    try {
                        img=ImageIO.read(file);
                        ImageIcon icon=new ImageIcon(img); // ADDED
                        label.setIcon(icon); // ADDED

                        Dimension imageSize = new Dimension(icon.getIconWidth(),icon.getIconHeight()); // ADDED
                        label.setPreferredSize(imageSize); // ADDED

                        label.revalidate(); // ADDED
                        label.repaint(); // ADDED
                    }
                    catch(IOException e1) {}
                }

                if (e.getSource()==button2){
                    comp.setVisible(true);
                }
            }
        };

        //ImageIcon icon=new ImageIcon(img); // REMOVED
        //JLabel label=new JLabel(icon); // REMOVED
        label = new JLabel(); // ADDED

        JPanel secpanel=new JPanel();
        ...

To explain what I've changed...

  1. The label will now be created as an empty JLabel when you first start the program. It is also stored as a global variable so we can access it later
  2. When the button is clicked, the img is created, as before, and then it is loaded into your label using setIcon();
  3. The label is resized, then revalidate() and repaint() to make sure that the image is drawn after it is set.

The ImageIO.read is only executed when that specific JButton is pressed. That is because it's inside the ActionListener. Because of this, img is null which causes a NullPointerException when ImageIcon icon=new ImageIcon(img) is executed.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!