2012-03-22 28 views
3

我在打開GUI窗口之前從命令行獲取輸入有一些麻煩。我之前在Apple Exchange上問過這個問題,但是在我們確定它是一個編程問題之後發送到了這裏。基本上,我運行掃描儀來獲取用戶輸入,然後打開一個窗口,但它啓動程序,切換我的Mac上的空間,然後我必須切換回帶有終端的工作空間來回答問題。這是原始問題的鏈接。如何在我的掃描儀之前調用GUI代碼?

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

} 
+3

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

回答

4

使用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]); 
      } 
     }); 
    } 
} 
+0

似乎有很多我誤解了。謝謝:) – CaldwellYSR 2012-03-23 17:12:40

+0

很高興幫助。部分問題是特定於Mac OS的問題,可在[其他線程](http://apple.stackexchange.com/a/45355/20589)中找到,但啓動新的JVM可在多個平臺上運行。另見['Launcher'](http://stackoverflow.com/a/5696404/230513)。 – trashgod 2012-03-23 17:19:02

0

代碼似乎是好的。在客戶端中是否存在任何類級別的東西(例如,靜態成員等)?

鏈接中的整個交換工作區描述是操作系統級別的東西,而不是專門用於Java的東西。

是否有選擇的Java命令或Mac上的東西,你可以使用?