gpt4 book ai didi

java - 处理 JDialog 后 JVM 不会关闭

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:47:44 24 4
gpt4 key购买 nike

我已经创建了 JDialog 的扩展。

public class ImageDialog extends JDialog implements ActionListener {
private JTextField textField;

public ImageDialog(JFrame parent, String title,
String message, BufferedImage bufferedImage) {
super(parent, title, true);
if (parent != null) {
Dimension parentSize = parent.getSize();
Point p = parent.getLocation();
setLocation(p.x + parentSize.width / 4, p.y + parentSize.height / 4);
}

this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
this.setModal(true);

JPanel frame = new JPanel();
frame.setLayout(new BoxLayout(frame, BoxLayout.Y_AXIS));

frame.add(new JLabel(message), BorderLayout.PAGE_START);

JLabel lblimage = new JLabel(new ImageIcon(bufferedImage));
frame.add(lblimage, BorderLayout.CENTER);

textField = new JTextField(1);

frame.add(textField, BorderLayout.PAGE_END);

getContentPane().add(frame);

JPanel buttonPane = new JPanel();
JButton button = new JButton("OK");
buttonPane.add(button);
button.addActionListener(this);
getContentPane().add(buttonPane, BorderLayout.SOUTH);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
pack();
setVisible(true);
}

public String getTextField() {
return textField.getText();
}

public void actionPerformed(ActionEvent e) {
setVisible(false);
dispose();
}
}

它运行良好并且做了它应该做的事情,除了 jvm 在使用后不会关闭。我使用它如下:

ImageDialog dlg = new ImageDialog(new JFrame(), "Important question", "How many fluffy bunnies do you see?", img);
System.out.println(dlg.getTextField());
dlg.dispose();

但是 JVM 只是在程序完成时卡在那里。有什么办法可以解决这个问题吗?

最佳答案

您需要为您的框架设置 setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

或者在任何其他地方:

frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

关闭对话框后程序将退出。

对于对话框,您应该设置 DISPOSE_ON_CLOSE 关闭操作属性。对话框依赖于框架。当您关闭框架时,您的程序将结束。

这就是为什么不要忘记让您的框架可见。

编辑

取而代之的是:

ImageDialog dlg = new ImageDialog(new JFrame(), "Screen captcha", "Enter the letters from the image", img);
System.out.println(dlg.getTextField());
dlg.dispose();

你应该有这样的东西:

JFrame f = new JFrame();
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.setVisible(true);
//ideally frame should have a button that creates the dialog and sets it to visible
// no need to dispose dialog here

关于java - 处理 JDialog 后 JVM 不会关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17495680/

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