java - 在 EDT 线程中,Swing JFrame 组件未在框架中绘制,即框架为空,但框架在主线程中成功绘制
问题描述
我正在尝试使用 JFrame 显示一个摆动对话框,同时在 EDT 线程中检查 SwingUtilities.isEventDispatchThread()。在主线程中,组件通过 SwingUtilities.invokeLater() 方法正确绘制,但在 EDT 线程中,添加到框架的组件不会出现。下面是代码:
private void showDialog(String title) {
frame = new JFrame();
frame.setTitle(title);
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
JButton cancelLogin = new JButton("cancel login");
cancelLogin.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
fireLoginCanceledEvent();
disposeFrame();
}
});
JPanel bottomPanel = new JPanel();
bottomPanel.add(cancelLogin);
panel.add(bottomPanel, BorderLayout.SOUTH);
JLabel info = new JLabel("login initiated...");
panel.add(info, BorderLayout.NORTH);
frame.getContentPane().add(panel);
frame.setLocationRelativeTo(null);
frame.setSize(300, 100);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setVisible(true);
}
private synchronized void disposeFrame() {
if (frame != null) {
if (frame.isDisplayable()) {
frame.dispose();
}
public void display() {
if (SwingUtilities.isEventDispatchThread()) {
showDialog(windowTitle); // Components not appearing
frame.revalidate();
frame.repaint();
} else {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
showDialog(windowTitle); // Components are correctly rendered
}
});
}
}
解决方案
推荐阅读
- sdn - 如何将openflow更新到1.3
- eslint - 使用 Eslint 时真的需要 Prettier 吗?
- kubernetes - 为什么 GKE Kubernetes 集群需要一个版本?
- c# - 如何通过wcf服务更新宿主项目中的winform控件?
- windows - ContainerContentChanging 事件和数据模型更改
- c++ - 注册对对象工厂的调用会导致段错误
- angular - 如何在Angular的http GET请求中传递多个参数?
- python - 尝试加载 Django 模板时出现错误
- find - 如何删除 printf cmd 在 bash 脚本中添加的 2 个额外的最后一个字符?
- r - 使用 R 在多行中查找模式