gpt4 book ai didi

java - JFileChooser - 打开/取消/退出按钮

转载 作者:行者123 更新时间:2023-12-01 07:11:19 26 4
gpt4 key购买 nike

我制作了一个按钮,它将创建一个 JFileChooser,以便用户可以打开一个 .txt 文件,这是按钮的操作监听器内的代码:

JFileChooser fc = new JFileChooser();
//filter-show only .txt files
FileNameExtensionFilter txtfilter = new FileNameExtensionFilter("txt files (*.txt)", "txt");

//apply the filter to file chooser
fc.setFileFilter(txtfilter);
fc.setDialogTitle("Otvori txt file");
//disable the ability to show files of all extensions
fc.setAcceptAllFileFilterUsed(false);
//create file chooser via jFrame
fc.showOpenDialog(jFrame);
//get selected file
File selFile = fc.getSelectedFile();
Path path = Paths.get(selFile.toString());
asdf = selFile.toString();
//display chosen file on jLabel5
jLabel5.setText(path.getFileName().toString());

如果您在文件选择器中选择 .txt 文件,它就可以正常工作,但如果您只选择一个文件,然后按取消并退出,它也可以工作。我认为这是因为 getSelectedFile() 但我想知道是否有一种方法可以确保用户选择一个文件并在文件选择器中按下打开作为获取文件的条件?

最佳答案

您应该检查返回值是否来自:

fc.showOpenDialog(jFrame) == JFileChooser.APPROVE_OPTION

该返回值指示用户如何退出对话框。

参见JFileChooser.showOpenDialog(Component) docs.

关于java - JFileChooser - 打开/取消/退出按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13779381/

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