这是我的程序。我必须从JFileChooser中选择一个文件,然后对其执行一些操作。问题是文件读取器在我可以选择文件之前先给出nullpointer
,说实话,我什至无法选择,因为当testo=new file reader(cavia)
出现时,什么也没出现,如果我尝试将其删除,正确,但我无法选择文件。
我能做什么?
public class Chooser {
static File cavia;
public static void main(String[] args) throws IOException {
JFrame quadro= new JFrame();
JFileChooser scelta= new JFileChooser();
quadro.setLayout(new GridLayout());
JButton apriselezione = new JButton("Selezionafle");
quadro.setBounds(20, 20, 300, 300);
FileReader testo;
scelta.setCurrentDirectory(new File (System.getProperty("user.home")+System.getProperty("file.separator")+"Desktop"));
apriselezione.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
scelta.showOpenDialog(apriselezione);
cavia=scelta.getSelectedFile();
}
});
testo= new FileReader(cavia);
apriselezione.setVisible(true);
quadro.add(apriselezione);
quadro.setVisible(true);
quadro.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
testo.close();
}
}
答案 0 :(得分:0)
这是您应该执行的操作(代码中有一些额外的注释和更改):
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class Chooser {
static File cavia;
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> { // All swing applications should run in their own thread
JFrame quadro = new JFrame();
JFileChooser scelta = new JFileChooser();
quadro.setLayout(new GridLayout());
JButton apriselezione = new JButton("Selezionafle");
quadro.setBounds(20, 20, 300, 300);
scelta.setCurrentDirectory(
new File(System.getProperty("user.home") + System.getProperty("file.separator") + "Desktop"));
apriselezione.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
scelta.showOpenDialog(apriselezione);
cavia = scelta.getSelectedFile();
try (FileReader testo = new FileReader(cavia)) { // try-with-resources
//Do something with filereader
} catch (IOException e2) {
e2.printStackTrace();
}
}
});
apriselezione.setVisible(true);
quadro.add(apriselezione);
quadro.setVisible(true);
quadro.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
});
}
}