gpt4 book ai didi

Java:JFileChooser 如何在文本字段中显示选定的文件

转载 作者:搜寻专家 更新时间:2023-11-01 02:14:50 25 4
gpt4 key购买 nike

我有一个 JFileChooser,我能够在控制台中打印绝对路径。我需要在用户选择文件后立即在文本字段中显示文件路径。

下面是代码,请告诉我怎么做。

        public void actionPerformed(ActionEvent ae) {

JFileChooser fileChooser = new JFileChooser();
int showOpenDialog = fileChooser.showOpenDialog(frame);

if (showOpenDialog != JFileChooser.APPROVE_OPTION) return;

如果您需要任何其他详细信息,请告诉我。

最佳答案

您需要监听在使用 JFileChooser 时发生的变化,请参见以下代码片段:

JFileChooser chooser = new JFileChooser();

// Add listener on chooser to detect changes to selected file
chooser.addPropertyChangeListener(new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
if (JFileChooser.SELECTED_FILE_CHANGED_PROPERTY
.equals(evt.getPropertyName())) {
JFileChooser chooser = (JFileChooser)evt.getSource();
File oldFile = (File)evt.getOldValue();
File newFile = (File)evt.getNewValue();

// The selected file should always be the same as newFile
File curFile = chooser.getSelectedFile();
} else if (JFileChooser.SELECTED_FILES_CHANGED_PROPERTY.equals(
evt.getPropertyName())) {
JFileChooser chooser = (JFileChooser)evt.getSource();
File[] oldFiles = (File[])evt.getOldValue();
File[] newFiles = (File[])evt.getNewValue();

// Get list of selected files
// The selected files should always be the same as newFiles
File[] files = chooser.getSelectedFiles();
}
}
}) ;

在第一个条件中,您需要做的就是设置文本字段的值以匹配新选择的文件名。看这个例子:

yourTextfield.setText(chooser.getSelectedFile().getName());

或者只是

yourTextfield.setText(curFile.getName());

类 File 中的 getName() 方法将为您提供所需的信息。从德 API docs 帮助你自己查看每个方法的作用。

关于Java:JFileChooser 如何在文本字段中显示选定的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8428548/

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