我有一个 JFrame,在我有 JButton 的框架上,我想要的是当单击该文件时,用户可以使用 java JFileChooser 加载文件。
我这样声明 FileChooser。
JFileChooser fc;
然后这是我在按钮的动作侦听器中的代码。
JButton btnLoad = new JButton("Load .txt");
btnLoad.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int returnVal = fc.showOpenDialog(OpenFile.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
//This is where a real application would open the file.
System.out.println("Opening: " + file.getName() + ".");
} else {
System.out.println("Open command cancelled by user.");
}
}
});
它产生的错误是
javax.swing.AbstractButton$Handler 的 javax.swing.AbstractButton.fireActionPerformed(Unknown Source) 的 maple.Netflix$2.actionPerformed(Netflix.java:73) 的线程“AWT-EventQueue-0”java.lang.NullPointerException 中的异常。 actionPerformed(Unknown Source) at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source) at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source) at javax.swing.DefaultButtonModel.setPressed(Unknown Source) at java.awt。 AWTEventMulticaster.mouseReleased(Unknown Source) at java.awt.Component.processMouseEvent(Unknown Source) at javax.swing.JComponent.processMouseEvent(Unknown Source) at java.awt.Component.processEvent(Unknown Source) at java.awt.Container。 java.awt.Component 中的 processEvent(Unknown Source)。dispatchEventImpl(Unknown Source) at java.awt.Container.dispatchEventImpl(Unknown Source) at java.awt.Component.dispatchEvent(Unknown Source) at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source) at java.awt.LightweightDispatcher.processMouseEvent( Unknown Source) at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source) at java.awt.Container.dispatchEventImpl(Unknown Source) at java.awt.Window.dispatchEventImpl(Unknown Source) at java.awt.Component.dispatchEvent(Unknown Source ) at java.awt.EventQueue.dispatchEventImpl(Unknown Source) at java.awt.EventQueue.access$200(Unknown Source) at java.awt.EventQueue$3.run(Unknown Source) at java.awt.EventQueue$3.run(Unknown源)在 java.security.AccessController.doPrivileged(Native Method) 在 java。security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source) at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source) at java.awt.EventQueue$4.run(Unknown Source) at java.awt.EventQueue$4.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source) at java.awt.EventQueue.dispatchEvent(Unknown Source) at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source) at java .awt.EventDispatchThread.pumpEventsForFilter(Unknown Source) at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source) at java.awt.EventDispatchThread.pumpEvents(Unknown Source) at java.awt.EventDispatchThread.pumpEvents(Unknown Source) at java.awt .EventDispatchThread。运行(未知来源)
这是第 73 行。
int returnVal = fc.showOpenDialog(Netflix.this);