关注这个问题,error message with JButton and JFileChooser,我希望有一个JButton来使用JFileChooser浏览文件。这是我们的代码:
package main;
import java.awt.Component;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Main {
private static Component frame;
private static String fullPath;
public static void main(String args[]) throws FileNotFoundException, IOException {
Date start_time = new Date();
try {
GridBagConstraints gbc = new GridBagConstraints();
JButton inputButton = new JButton("Browse input file");
final JFileChooser inputFile = new JFileChooser();
inputFile.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
JPanel myPanel = new JPanel(new GridBagLayout());
myPanel.add(inputButton, gbc);
inputButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser inputFile = new JFileChooser();
inputFile.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
if (inputFile.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
File file1 = inputFile.getSelectedFile();
String fullpathTemp = (String) file1.getAbsolutePath();
fullpathTemp = fullPath;
}
}
});
Date stop_time = new Date();
double etime = (stop_time.getTime() - start_time.getTime()) / 1000.;
System.out.println("\nElapsed Time = " + etime + " seconds\n");
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
} finally {
}
}
}
问题是点击“浏览输入文件”按钮并选择文件后,一旦点击“确定”,我就会收到以下错误消息:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at main.Main$1.actionPerformed(Main.java:195)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)
答案 0 :(得分:3)
您已宣布inputFile
3次
一次作为静态类变量
private static JFileChooser inputFile;
然后在你的main
方法
final JFileChooser inputFile = new JFileChooser();
// this can't possible compile
inputfile.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
然后在ActionListener
inputButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser inputFile = new JFileChooser();
inputFile.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
if (inputFile.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
File file1 = inputFile.getSelectedFile();
String fullpathTemp = (String) file1.getAbsolutePath();
fullpathTemp = fullPath;
}
}
});
这些中的任何一个都应该可以相互干扰,这会产生我能看到的NullPointerException
,但鉴于你的代码示例实际上不会编译,我只能想象我们是没有看到一切