gpt4 book ai didi

java - 自定义模态对话框

转载 作者:行者123 更新时间:2023-12-02 00:09:20 24 4
gpt4 key购买 nike

我正在创建自己的对话框,它基本上是一个设置为 JFrame 上玻璃面板的 JPanel。我想让我的对话框成为模态对话框,即当对话框可见时,不会执行 setVisible() 之后的所有代码,并且一旦对话框关闭,setVisible() 之后的其余代码必须继续。

为了实现此目的,我使用线程来显示我的对话框。我知道必须使用 SwingUtilities.invokeLater() 方法来更新 gui,因为它是在另一个线程中执行的。但是我的对话框没有显示在屏幕上。

这是我的代码示例:

final JFrame frame = new JFrame();
frame.setBounds(0, 0, 1024, 768);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);

JButton button = new JButton("Text");
button.setBounds(200, 300, 110, 50);
button.addActionListener(new ActionListener() {

boolean dispose;

public void actionPerformed(ActionEvent e) {
try {
Thread thread = new Thread(new Runnable() {
public void run() {
final JPanel panelGlass = new JPanel(null);
panelGlass.setBounds(frame.getBounds());
panelGlass.setBackground(Color.red);
frame.setGlassPane(panelGlass);

JButton btnClose = new JButton("close");
btnClose.setBounds(100, 100, 110, 50);
btnClose.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dispose = true;
}
});
panelGlass.add(btnClose);

SwingUtilities.invokeLater(new Runnable() {
public void run() {
dispose = false;
panelGlass.setVisible(true);
}
});

while (!dispose) {
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
panelGlass.setVisible(false);
}
});
thread.start();
thread.join();
} catch (Exception ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
frame.getContentPane().add(button);

frame.setVisible(true);

为什么我的对话框没有显示?

最佳答案

问题出在这里:

thread.start();
thread.join();

您启动了线程,但立即等待它完成。这会阻塞 UI 线程,并不允许它处理您的 SwingUtilities.invokeLater 更新。

我真的看不出 join 调用存在的任何充分理由。

关于java - 自定义模态对话框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13180909/

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