gpt4 book ai didi

java - FileReader 和 ActionListener 之间的同步问题,在我给他任何勇气之前,FileReader 给出了空指针;

转载 作者:太空宇宙 更新时间:2023-11-04 09:52:15 27 4
gpt4 key购买 nike

这是我的程序。我必须从 JFileChooser 选择一个文件,然后对其执行一些操作。问题是,在我选择文件之前,filereader 给出了 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();
}
}

最佳答案

以下是您应该如何执行此操作(代码中的一些额外注释和更改):

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);
});
}
}

关于java - FileReader 和 ActionListener 之间的同步问题,在我给他任何勇气之前,FileReader 给出了空指针;,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54571817/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com