gpt4 book ai didi

java - 处理 JFileChooser 窗口关闭?

转载 作者:行者123 更新时间:2023-12-02 08:04:51 25 4
gpt4 key购买 nike

我有一个创建的 JFileChooser,如下所示:

JFileChooser chooser = new JFileChooser();
int choosen = chooser.showOpenDialog(fileSelector.this);

if (choosen == JFileChooser.CANCEL_OPTION) {
System.out.println("Closed");
}

如果我关闭窗口而不进行选择,则会收到错误:

Exception in thread "main" java.lang.NullPointerException
at fileSelector.fileSelector(fileSelector.java:32)
at createAndControl.main(createAndControl.java:15)

我想知道处理这个问题的正确方法是什么,我应该在窗口关闭时调用什么操作来避免这种情况?

TIA

最佳答案

建议反过来做:

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {

@Override
public void run() {
JFileChooser fc = new JFileChooser();
int returnVal = fc.showOpenDialog(null);

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() + ".\n");
} else {
System.out.println("Open command cancelled by user.\n");
}
}
});
}

关于java - 处理 JFileChooser 窗口关闭?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8346058/

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