概要
我正在开发一个Java Swing项目,我已经在IntelliJ IDEA中通过直接运行main方法成功调试了。关闭框架后,调试器正常退出。
但是,在向项目添加 JFileChooser
对话框后,调试器无法正常退出。我现在每次都必须单击停止按钮,这会导致 JVM 以非零状态退出。
最小的、可重复的示例
这是导致问题的代码部分;这是一个 ActionListener
,我将其添加到启动 JFileChooser
的两个按钮中:
/**
* Generic action listener that is used for both file selection dialog buttons
*/
private final ActionListener fileSelectionButtonActionListener = new ActionListener()
{
@Override
public void actionPerformed(final ActionEvent event)
{
final String target = ((JButton) event.getSource()).getName();
assert (target.equals("file") || target.equals("directory"));
JFileChooser fileChooser = new JFileChooser(new File(".").getAbsoluteFile());
fileChooser.setDialogType(JFileChooser.OPEN_DIALOG);
if(target.equals("directory")) {
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
}
final int result = fileChooser.showOpenDialog(new JFrame());
if(result == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
if(target.equals("file")) {
fileTextField.setText(selectedFile.getAbsolutePath());
} else {
directoryTextField.setText(selectedFile.getAbsolutePath());
}
}
}
};
调试步骤
我尝试将 JFrame
创建从 showOpenDialog
方法的参数移动到变量声明,并添加 frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
但这并没有解决问题。这几乎就像框架仍然卡在内存中一样,这就是 JVM 不会关闭的原因。
问题
如何在使用 JFileChooser
时使 JVM 适当关闭?
最佳答案
问题确实是,JFrame
仍在内存中,导致 JVM 挂起。但是,解决方案是不需要 JFrame
。
不要将 new JFrame()
设置为对话框的父级,而是将父级设置为对话框窗口本身:
/**
* Generic action listener that is used for both file selection dialog buttons
*/
private final ActionListener fileSelectionButtonActionListener = new ActionListener()
{
@Override
public void actionPerformed(final ActionEvent event)
{
final String target = ((JButton) event.getSource()).getName();
assert (target.equals("file") || target.equals("directory"));
JFileChooser fileChooser = new JFileChooser(new File(".").getAbsoluteFile());
fileChooser.setDialogType(JFileChooser.OPEN_DIALOG);
if(target.equals("directory")) {
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
}
--> final int result = fileChooser.showOpenDialog(fileChooser); <--
if(result == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
if(target.equals("file")) {
fileTextField.setText(selectedFile.getAbsolutePath());
} else {
directoryTextField.setText(selectedFile.getAbsolutePath());
}
}
}
};
更改获得结果的行:final int result = fileChooser.showOpenDialog(fileChooser);
。这样做可以解决问题。
关于java - 将 JFileChooser 添加到我的项目后,IntelliJ 调试器不会停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58083225/