2

Simple code from java.sun:

public class BasicApp implements Runnable {

    JFrame mainFrame;
    JLabel label;

    public void run() {
        mainFrame = new JFrame("BasicApp");
        label = new JLabel("Hello, world!");
        label.setFont(new Font("SansSerif", Font.PLAIN, 22));
        mainFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        mainFrame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                mainFrame.setVisible(false);
                // Perform any other operations you might need
                // before exit.
                System.exit(0);
            }
        });
        mainFrame.add(label);
        mainFrame.pack();
        mainFrame.setVisible(true);
    }

    public static void main(String[] args) {
        Runnable app = new BasicApp();
        try {
            SwingUtilities.invokeAndWait(app);
        } catch (InvocationTargetException ex) {
            ex.printStackTrace();
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
    }
}

I can put all of this method into main(), but why do I need a separate run method that also implements the runnable to execute it? What is the idea behind this concept? Thanks.

4

3 回答 3

9

来自 Oracle SDN:线程和 Swing

一旦实现了一个 Swing 组件,所有可能影响或依赖于该组件状态的代码都应该在事件调度线程中执行。

它的要点是代码需要在 Swing 良好并准备好运行时运行。调用它时不一定正确。

于 2011-11-10T13:41:34.243 回答
1

方法 run() 在单独的线程中启动。因此,您的 GUI 部分从其他应用程序“独立”工作,并且在绘图期间不要停止它。

于 2011-11-10T13:39:52.013 回答
0

如果您打算在线程中运行代码,那么您需要实现runnable接口。实现runnable接口时,需要实现run()方法。

于 2011-11-10T13:36:20.900 回答