为什么我需要一个可运行程序而不是直接从 main 调用?
来自 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();
}
}
}
我可以将所有这些方法放入 main() 中,但是为什么我需要一个单独的 run 方法来执行它,该方法也实现了 runnable ?这个概念背后的想法是什么?谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
来自 Oracle SDN:线程和 Swing
其要点是,代码需要在 Swing 良好并准备好运行时运行。当你调用它时不一定是正确的。
From Oracle SDN: Threads and Swing
The gist of it is that the code needs to be run when Swing is good and ready to run it. Not necessarily right when you call it.
run() 方法在单独的线程中启动。因此,您的 GUI 部分可以与其他应用程序“独立”工作,并且在绘图期间不会停止它。
Method run() is started in separated Threads. So your GUI part work "standalone" from other application and don't stop it during drawing.
如果您打算在线程中运行代码,那么您需要实现
runnable
接口。当您实现runnable
接口时,您需要实现run()
方法。If you intend to run your code in threads, then you'd need to implement the
runnable
interface. When you implement therunnable
interface, you need to implement therun()
method.