我有一個JFrame,並在框架上我有JButton,我想要的是當單擊該文件,用戶可以使用Java JFileChooser加載文件。打開文件會產生一個java.lang.NullPointerException
我聲明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.");
}
}
});
,它是生產我的錯誤是
異常在線程 「AWT-EventQueue的-0」 顯示java.lang.NullPointerException 在maple.Netflix $ 2.actionPerformed(Netflix.java:73 ) 在javax.swing.AbstractButton.fireActionPerformed(來源不明) 在javax.swing.AbstractButton中的$ Handler.actionPerformed(來源不明) 在javax.swing.DefaultButtonModel.fireActionPerformed(來源不明) 在javax.swing.ButtonModel中。 setPressed(未知來源) at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source) at java.awt.AWTEventMulticaster.mouseReleased(Unknown Source) at java.awt.Component.processMouseEvent(Unknown Source) at javax.swing.JComponent (未知源) at java.awt.Component.processEvent(Unknown Source) at java.awt.Container.processEvent(Unknown Source) at java.awt.Component.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 Sourc E) 在java.awt.LightweightDispatcher.dispatchEvent(未知來源) 在java.awt.Container.dispatchEventImpl(未知來源) 在java.awt.Window.dispatchEventImpl(未知來源) 在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 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(未知來源) 在java.awt.EventQueue.dispatchEvent(未知來源) 在java.awt.EventDispatchThread.pumpOneEventForFilters(未知來源) 在java.awt.EventDispatchThread.pumpEventsForFilter(未知來源) 在java.awt中.EventDispatchThread.pumpEventsForHierarchy(Unknown Source) at java.awt.EventDispatchT(java.awt.EventDispatchThread.pumpEvents(Unknown Source)) at java.awt.EventDispatchThread.pumpEvents(Unknown Source) at java.awt.EventDispatchT hread.run(Unknown Source)
這是73行。
int returnVal = fc.showOpenDialog(Netflix.this);