How do I call the GUI code in front of my scanner?
I'm having trouble getting input from the command line before opening the GUI window. I previously asked this question on Apple Exchange, but was posted here after we identified it as a programming problem. Basically I run the scanner to get user input before opening the window, but it launches the program by changing spaces on my Mac, and then I have to go back to the workspace with the terminal in it to answer the question. Here's a link to the original question.
Here's the code I tested with ...
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);
}
}
source to share
Use invokeLater()
to launch the GUI after receiving input.
final String response = in.nextLine();
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new Client(response);
}
});
Please note that your example works fine on my platform due to the time difference. Also consider using an array args
to pass parameters or refer to the implementation as shown inFullScreenTest
Addendum: read a little different thread , you can use the following approach which runs 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]);
}
});
}
}
source to share
The code looks fine. Are there any class level items in the client that you didn't show here (like static members, etc.?)
All description of workstations of switches in your link is a subject of OS OS NOT NOT.
Are there options for java command or something on mac that you could use?
source to share