使用窗口构建器时的默认GUI代码如下。
import java.awt.EventQueue;
import javax.swing.JFrame;
public class Goo {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Goo window = new Goo();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Goo() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
我想从另一个类作为一个线程运行它。所以其他课程看起来像,
public class GooRun {
public static void main(String[] args) {
// TODO Auto-generated method stub
Goo myGoo = new Goo();
Thread myThread = new Thread(myGoo);
myThread.start();
}
}
我不完全理解当你不使用实现Runnable或扩展Thread时run方法如何工作。
我得到的错误是构造函数未定义Thread(Goo)未定义。
你可以做以下两件事之一:
第一个选项:使myGoo
实现Runnable
:
public class Goo implements Runnable{
然后在run
中添加Goo
方法:
@Override
public void run() {
try {
Goo window = new Goo();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
之后,你可以像在其他main
那样做:
public static void main(String[] args){
Goo myGoo = new Goo();
Thread myThread = new Thread(myGoo);
myThread.start();
}
基本上,这使得Goo
成为可以在线程启动时启动的东西(因此实现Runnable
)。
选项2:在你的main
中,你可以用runnable创建一个线程:
public static void main(String[] args){
Thread t = new Thread(new Runnable() {
@Override
public void run() {
Goo myGoo = new Goo();
}
});
t.start();
}
ItamarG3的解决方案1实际上是一个坏主意。在这种情况下,你有run()
的2个实例(一个来自main()
,一个来自Goo
),而你不需要它们。
你应该在this.frame.setVisible(true);
中调用run()
,而不是new
另一个Goo
实例。