首页 > 解决方案 > 在 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
            }
        });
   }
  }

标签: javamultithreadingswing

解决方案


推荐阅读