且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java框架在while循环中无法正确显示

更新时间:2023-02-03 12:20:26

在不知道您尝试做的全部工作的情况下,您不可能完全获得确切的答案.

Without knowing the full extent of what you are trying to do, it's not entirely possible to you an exact answer.

从事物的声音中,您尝试在事件调度线程的上下文中运行长时间运行的任务.除其他事项外,该线程负责处理重画请求.

From the sounds of things your trying to run long running tasks within the context of the Event Dispatching Thread. This thread is responsible for, amongst other things, processing repaint requests.

阻止此线程,防止Swing重新绘制自身.

Blocking this thread, prevents Swing from repainting itself.

据我所知,您想使用 SwingWorker .这样,您就可以在后台线程中执行工作,同时将更新重新同步回EDT

From what I can tell, you want to use a SwingWorker. This will allow you to performing your work in a background thread, while re syncing updates back to the EDT

已更新示例

我知道您说过不希望使用SwingWorker,但是说实话,这只是更简单,更安全...

I know you said didn't "want" to use a SwingWorker, but to be honest, it's just simpler and safer...

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingWorker;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class LongRunningTask {

    public static void main(String[] args) {
        new LongRunningTask();
    }

    public LongRunningTask() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                new BackgroundWorker().start();

            }
        });
    }

    public class BackgroundWorker extends SwingWorker<Object, Object> {

        private JFrame frame;

        public BackgroundWorker() {
        }

        // Cause exeute is final :P
        public void start() {
            ImageIcon icon = new ImageIcon(getClass().getResource("/spinner.gif"));
            JLabel label = new JLabel("This might take some time");
            label.setIcon(icon);

            frame = new JFrame("Testing");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setLayout(new GridBagLayout());
            frame.add(label);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);

            execute();
        }

        @Override
        protected Object doInBackground() throws Exception {

            System.out.println("Working hard...");
            Thread.sleep(1000 + (((int)Math.round(Math.random() * 5)) * 1000));
            System.out.println("Or hardly working...");

            return null;

        }

        @Override
        protected void done() {
            frame.dispose();
        }

    }
}