[英]Java running main method of other class, when JButton is pressed
我正在尝试开发一个JFrame,它有两个按钮,可以让我调用其他类的main方法。 第一次尝试是将它直接放入每个按钮的actionPerformed中,这将导致另一个类的JFrame打开但只显示它的标题而不显示JPanel的任何内容另外冻结程序(甚至不能按关闭按钮,必须进入任务管理器或eclipse才能杀死它)。 第二个尝试是在actionPerformed中添加一个方法调用,并且这次添加方法将调用其他类的main方法,但结果相同(冻结程序)。
出于测试目的,我已经调用了其他类的main方法,直接在这个类main方法中向我证明了其他类的框架已成功出现,包括其所有JPanel内容,功能等。
我知道我可以在我的main方法中进行某种无限循环,等待布尔值设置为true,但是我必须有一些更便宜的方法来使它工作。 所以我在这里向你问这个问题。
这是第二次尝试的代码;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Chat {
public static void main (String[] args) {
JFrame window = new JFrame("Chat Selection");
//Set the default operation when user closes the window (frame)
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Set the size of the window
window.setSize(600, 400);
//Do not allow resizing of the window
window.setResizable(false);
//Set the position of the window to be in middle of the screen when program is started
window.setLocationRelativeTo(null);
//Call the setUpWindow method for setting up all the components needed in the window
window = setUpWindow(window);
//Set the window to be visible
window.setVisible(true);
}
private static JFrame setUpWindow(JFrame window) {
//Create an instance of the JPanel object
JPanel panel = new JPanel();
//Set the panel's layout manager to null
panel.setLayout(null);
//Set the bounds of the window
panel.setBounds(0, 0, 600, 400);
JButton client = new JButton("Run Client");
JButton server = new JButton("Run Server");
JLabel author = new JLabel("By xxx");
client.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//run client main
runClient();
}
});
server.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//run server main
}
});
panel.add(client);
client.setBounds(10,20,250,200);
panel.add(server);
server.setBounds(270,20,250,200);
panel.add(author);
author.setBounds(230, 350, 200, 25);
window.add(panel);
return window;
}
private static void runClient() {
String[] args1={"10"};
ClientMain.main(args1);
}
}
每个应用程序只允许一种主要方法。 老实说,当你在其他课程上调用main时,我不确定你想要做什么或想到应该发生什么。 当你在其他类上调用main时,你所做的就是调用一个恰好被称为main的方法并将args传递给它。 你的冻结可能是因为你没有正确使用Swing:
http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
您遇到的问题是Java Swing是单线程的。 当您运行另一个类的main函数时,无论如何操作,GUI都将无法继续运行直到它返回。 尝试生成一个调用第二个主要方法的新线程。
private static void runClient() {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
String[] args1={"10"};
ClientMain.main(args1);
}
});
}
编辑:更新,根据@ Radiodef的建议。 当你说第二堂课必须在GUI上显示东西时,错过了顶部。 肯定想和invokeLater一起去。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.