我在打开 GUI 窗口之前从命令行获取输入时遇到了一些问题。我之前在 Apple Exchange 上问过这个问题,但在我们确定它是一个编程问题后被发送到这里。基本上我在打开一个窗口之前运行一个扫描仪来获取用户输入,但它会启动程序,在我的 Mac 上切换空间,然后我必须切换回带有终端的工作区来回答问题。这是原始问题的链接。
这是我测试过的代码...
public class Client extends JFrame {
public static void main(String[]args) {
Scanner in = new Scanner(System.in);
System.out.printf("\nGive me a size for the screen: ");
String response = in.nextLine();
new Client(response);
}
public Client(String title) {
super(title);
super.setVisible(true);
}
}
最佳答案
使用invokeLater()
在您获得输入后启动 GUI。
final String response = in.nextLine();
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new Client(response);
}
});
请注意,由于时间差异,您的示例在我的平台上运行良好。也可以考虑使用args
数组来传递参数,或者问实现,如图FullScreenTest
附录:阅读您的 other thread再近一点,您可以使用以下方法在单独的 JVM 中启动 NamedFrame
。
package cli;
import java.awt.EventQueue;
import java.io.IOException;
import java.util.Scanner;
import javax.swing.JFrame;
/** @see https://stackoverflow.com/q/9832252/230513 */
public class CommandLineClient {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Give me a name for the screen: ");
final String response = in.nextLine();
try {
ProcessBuilder pb = new ProcessBuilder(
"java", "-cp", "build/classes", "cli.NamedFrame", response);
Process proc = pb.start();
} catch (IOException ex) {
ex.printStackTrace(System.err);
}
}
}
class NamedFrame extends JFrame {
public NamedFrame(String title) {
super(title);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationByPlatform(true);
setVisible(true);
}
public static void main(final String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
JFrame f = new NamedFrame(args[0]);
}
});
}
}
关于java - 如何在我的扫描器之前调用 GUI 代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9832252/