使用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]);
}
});
}
}
搖擺GUI對象應當被構造和操作的_only_ [事件調度線程]上(http://download.oracle.com/javase/tutorial/uiswing/concurrency/initial.html)。 – trashgod 2012-03-22 23:52:41