gpt4 book ai didi

java - 遇到 Java 的 FileChooser 问题

转载 作者:行者123 更新时间:2023-11-30 08:55:51 25 4
gpt4 key购买 nike

我正在从事一项科学研究项目,我不想使用 Excel,而是想使用自己的代码来分析数据。我保存了一个 '.txt' 文件,其中包含 10,000 个数据点,这些数据点由制表符和硬回车分隔。现在,我正在尝试使用这段代码来更好地选择要审查的文件,但实际上它从来没有让我使用 getFile() 发送文件,我的问题是:为什么它会循环永远永远不会使用该文件?

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;

public class SimpleFileChooser extends JFrame {
public File sf;
public SimpleFileChooser() {
super("File Selector");
setSize(350, 200);
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container c = getContentPane();
c.setLayout(new FlowLayout());
JButton openButton = new JButton("Open");
final JLabel statusbar = new JLabel("Select a File");
openButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
JFileChooser chooser = new JFileChooser();
int option = chooser.showOpenDialog(SimpleFileChooser.this);
if (option == JFileChooser.APPROVE_OPTION) {
sf = chooser.getSelectedFile();
}
}
});
c.add(openButton);
c.add(statusbar);
}

public File getFile(){
return sf;
}
}

最佳答案

您正在使用 ActionListener 在用户按下 openButton 时触发文件选择。此监听器不会阻塞您当前的线程(操作事件正在 Event Dispatch Thread 上运行),因此您可以完成 SimpleFileChooser 的实例化,然后调用 #getFile() 在用户有机会选择文件之前。

你可以围绕你的代码构建一些东西让它等待 Action 事件发生,或者你可以摆脱那个框架和监听器,因为你不需要它们:

 public class SimpleFileChooser {
private final JFileChooser chooser;

public SimpleFileChooser() {
chooser = new JFileChooser();
chooser.setDialogTitle("Select a File");
}

public File getFile() {
int option = chooser.showOpenDialog(null);
if (option == JFileChooser.APPROVE_OPTION) {
return chooser.getSelectedFile();
}
return null;
}
}

你可以像你已经做的那样调用它:

SimpleFileChooser sfc = new SimpleFileChooser();
Trial test = new Trial(sfc.getFile());

因为您可以多次调用 #getFile(),您应该重用 SimpleFileChooser 实例,因为它的创建有点昂贵。

关于java - 遇到 Java 的 FileChooser 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28843699/

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