有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在我的扫描仪之前调用GUI代码?

我在打开GUI窗口之前从命令行获取输入时遇到一些问题。我之前在Apple Exchange上问过这个问题,但在我们确定这是一个编程问题后,我被送到了这里。基本上,在我打开窗口之前,我正在运行一个扫描仪来获取用户输入,但它会启动程序,在我的Mac电脑上切换空间,然后我必须切换回工作区,让终端在其中回答问题。这里有一个到原始问题的链接

https://apple.stackexchange.com/questions/45058/lion-fullscreen-desktop-switching-quirk/45065#comment51527_45065

这是我测试过的代码

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);
  }

}

共 (2) 个答案

  1. # 1 楼答案

    代码似乎没问题。客户机中是否有任何类级别的内容没有在此处显示(例如静态成员等)

    链接中的整个交换工作区描述是操作系统级的,而不是java

    在mac上有java命令或其他你可以使用的选项吗

  2. # 2 楼答案

    在获得输入后,使用^{}启动GUI

        final String response = in.nextLine();
        EventQueue.invokeLater(new Runnable() {
    
            @Override
            public void run() {
                new Client(response);
            }
        });
    

    请注意,由于时间差异,您的示例在我的平台上运行良好。还考虑使用^ {< CD2>}数组传递参数,或请求实现,如{a2}

    所示。

    附录:仔细阅读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]);
                }
            });
        }
    }