Javax.swing:如何正确显示组件的更新?

Zac*_*lle 3 java swing

我正在编写一个简单的Knight's Tour程序,带有图形显示.我已经编写了它来使用控制台,现在我正在尝试将代码转移到它以便它可以与swing一起使用.我有一个按钮,其动作监听器启动并运行该过程.这是代码:

askButton.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {

            int[][] tour = getBoard(); // generates a matrix representing a successful knight's tour
            int count = 0;

            while (count < 64) {
                count++;
                Location loc = searchFor(count, tour); //gets the location of the int "count" inside the matrix "tour"
                board.setVisible(false); //board contains a matrix of JPanels called "grid".
                grid[loc.row()][loc.column()].add(new JLabel("" + count)); //adds JLabel to JPanel with the proper number
                board.setVisible(true); //reset to visible to show changes
                delay(1000); //wait 1000 milliseconds - one second - to allow user to view changes
            }
        }
    });
Run Code Online (Sandbox Code Playgroud)

这就是代码.我希望每个数字单独显示,中间间隔一秒,但是当它站立时,框架会变成空白一段时间,并突然显示所有数字显示的结果,一旦完成.有人可以帮忙吗?谢谢.

mKo*_*bel 5

将所有答案放在一起

1.don't通话sleep(int),wait(int)代码中执行从AWT/Swing的监听器,使用

要么

  • 所有输出到Swing GUI必须以代码的形式包装在invokeLater

2. add/ remove/ modify已经可见的容器需要打电话

  • revalidate()并且repaint(),thenaftersetVisible()

3. setVisible必须用invokeLater自然的代码包裹在里面