使用窗口生成器时的默认 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();
}
}
当您不使用implements Runnable或extends Thread时,我不完全理解run方法是如何工作的。
我得到的错误是构造函数未定义 Thread(Goo) 未定义。
最佳答案
您可以执行以下两项操作之一:
第一个选项:使 myGoo
实现 Runnable
:
public class Goo implements Runnable{
然后在Goo
中添加一个run
方法:
@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
中,你可以创建一个带有可运行对象的线程:
public static void main(String[] args){
Thread t = new Thread(new Runnable() {
@Override
public void run() {
Goo myGoo = new Goo();
}
});
t.start();
}
关于java - 如何在 Java 中将 GUI 文件作为另一个类的线程来运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41173225/