我试图写入一个代码, 将使用 JFileChoooser 选中的图像显示为另一个 JFrame 。 我尝试了下面的代码, 但只有以下错误 。
Exception in thread "main" java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(ImageIcon.java:228)
at power.<init>(fCGUI.java:53)
at fCGUI.main(fCGUI.java:11)
这是代码:
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class fCGUI
{
public static void main(String []args)
{
power p=new power();
p.setVisible(true);
}
}
class power extends JFrame
{
JFileChooser chooser;
BufferedImage img;
JButton button,button2;
JFrame comp;
String filename;
File file ;
public power()
{
setSize(450,450);
panel.setLayout(new BorderLayout());
JPanel panel=new JPanel();
getContentPane().add(panel);
button =new JButton("press");
panel.add(button,BorderLayout.NORTH);
chooser = new JFileChooser();
ActionListener action=new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if (e.getSource()==button)
{
chooser.showOpenDialog(null);
file = chooser.getSelectedFile();
try
{
img=ImageIO.read(file);
}
catch(IOException e1) {}
}
if (e.getSource()==button2)
{
comp.setVisible(true);
}
}
};
ImageIcon icon=new ImageIcon(img);
JLabel label=new JLabel(icon);
JPanel secpanel=new JPanel();
comp=new JFrame();
comp.setSize(650,500);
comp.setLayout(new BorderLayout());
comp.setTitle("View Report");
JRootPane compPane=comp.getRootPane();
Container contePane=compPane.getContentPane();
contePane.add(secpanel);
secpanel.add(label,BorderLayout.CENTER);
button2=new JButton("access");
button2.addActionListener(action);
button.addActionListener(action);
panel.add(button2,BorderLayout.SOUTH);
}
}