How is GUI code being invoked before my Scanner?

核能气质少年 提交于 2019-12-01 21:07:04
trashgod

Use invokeLater() to start the GUI after you get the input.

    final String response = in.nextLine();
    EventQueue.invokeLater(new Runnable() {

        @Override
        public void run() {
            new Client(response);
        }
    });

Note that your example runs fine on my platform due to timing differences. Also consider using the args array to pass parameters, or ask the implementation, as shown in FullScreenTest

Addendum: Reading your other thread a little closer, you can use the following approach that launches a NamedFrame in a separate JVM.

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

Code appears to be ok. Is there any class level stuff in Client that you haven't shown here (e.g. static members etc?)

The whole switching workspaces description in your link is an OS level thing NOT java specifically.

Is there options to the java command or something on mac you could use?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!