在这个问题之后,JButton 和 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)