我正在编写一个程序来从两个文本文件收集信息以添加到数据库中的表中。为了允许用户选择他自己的文件,我创建了一个名为的非静态方法chooseFile()
使用JFileChooser
班级呈现showOpenDialog
(我也尝试过将其作为静态方法,得到相同的结果。如果这听起来像我猜测的那样,那么你是对的 - 我对编程只是马马虎虎)。
我的理解是调用 Swing 类main()
应该使用invokelater
。对于一次调用,这一切都运行良好(JVM 成功退出)chooseFile()
,但是当我添加第二个调用时chooseFile()
JVM 无限期地保持运行。但是,程序正常退出,两次调用chooseFile()
如果我这样做而不使用invokelater
。添加System.exit(0)
第二次打电话后invokelater
也可以让程序正常退出。
据我所知,在所有(非守护进程)线程关闭之前,程序不会退出。但是,我认为使用的目的invokelater
的目的是将所有非线程安全的 Swing 相关活动推送到 EDT 上。正在使用System.exit(0)
这里的最佳实践还是还有其他我应该知道的事情?
这是我的 SSCCE:
package ptMngr;
import java.io.IOException;
import java.nio.file.Path;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;
public class ParticipantManager {
private Path chooseFile() throws IOException{
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("Text Files", "txt","csv");
chooser.setFileFilter(filter);
int returnVal = chooser.showOpenDialog(null);
if(returnVal == JFileChooser.APPROVE_OPTION) {
System.out.println("You chose to open this file: " +
chooser.getSelectedFile().getName());
}
Path path = chooser.getSelectedFile().toPath();
return path;
}
/**
* @param args the command line arguments
*/
public static void main(String[] args){
// ParticipantManager pm = new ParticipantManager();
// try {
// pm.chooseFile();
// pm.chooseFile();
//
// } catch (IOException ex) {
// Logger.getLogger(ParticipantManager.class.getName()).log(Level.SEVERE, null, ex);
// }
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
ParticipantManager pm = new ParticipantManager();
try {
pm.chooseFile();
pm.chooseFile();
System.exit(0);
} catch (IOException ex) {
Logger.getLogger(ParticipantManager.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
}
在您致电时showOpenDialog(null)
你过关了null
作为父组件JFileChooser
。自从我和你一起工作以来已经有一段时间了JFileChooser
,但我似乎记得,当null
被传入。在此用例中,可能会创建两个“神奇”JFrame,并且它们会阻止终止。
您可能想尝试创建一个JFrame
作为两者的父级JFileChooser
因此它不会创建自动框架。
EDIT:
我的第一个想法是:
public static class ParticipantManager {
JFrame frame;
private JFrame getFrame() {
if (frame==null) {
frame = new JFrame();
frame.setSize(600, 400);
frame.setLocationRelativeTo(null);
// frame.setVisible(true); // <---- worked for me without this call too
}
return frame;
}
private void close() {
frame.dispose();
}
private Path chooseFile() throws IOException{
JFrame f = getFrame();
...
int returnVal = chooser.showOpenDialog(f);
...
...
pm.chooseFile();
pm.chooseFile();
pm.close(); // <----- close the frame
...
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)