2012-05-21 31 views
2

我需要通過gui向用戶顯示一些相關信息(如簡介,是/否問題和其他問題),然後gui進入響應進入控制檯。但是,我不能爲了我的生活而想到或者想辦法做到這一點。我如何運行GUI但仍然允許輸入到控制檯中?這裏有一些減少的代碼,顯示了我想要做的事情。我從一個處理容器東西的pps框架類來做這件事。我只需要添加按鈕,文本字段以及稍後的動作事件。將相關輸入/輸出輸出到GUI,在控制檯中接收到輸入

public class gui extends XFrame 
{ 
    private JTextField[] textFieldsUneditable; 

     public gui() 
     { 
      super(); 
      textFieldsUneditable = new JTextField[10]; 
      for(int i=0; i<textFieldsUneditable.length; i++) 
      { 
       textFieldsUneditable[i] = new JTextField(42); 
       textFieldsUneditable[i].setEditable(false); 
       add(textFieldsUneditable[i]); 
      } 

      revalidate(); 
      repaint(); 
     } 

     public void paintComponent(Graphics g) 
     { 
      super.paintComponent(g); 
      // code code code 
     } 

但我已經是其他的方法,而我希望用戶在控制檯迴應後運行,然後輸出到GUI中使用的setText這些不可編輯的JTextField的。我希望這是有道理的!

+0

爲什麼不使用GUI輸入的值也? – dacwe

+0

我需要分階段做,這是其中一個階段.. :( – user1396316

回答

1

我會做這樣的事情(下面的例子):

  1. 創建GUI並保存到你想要更新
  2. 獲取控制檯輸入線,由線等領域的引用,可能使用Scanner
  3. 找到您要更新
  4. 使用使用SwingUtilities.invokeAndWaitinvokeLater
  5. 重複3和4,直到你完成一個線程安全的方式更新的領域。

public static void main(String[] args) throws Exception { 

    // create a new frame 
    JFrame frame = new JFrame("Test"); 
    frame.setLayout(new GridLayout(0, 1)); 

    // create some fields that you can update from the console 
    JTextField[] fields = new JTextField[10]; 
    for (int i = 0; i < fields.length; i++) 
     frame.add(fields[i] = new JTextField("" + i)); // add them to the frame 

    // show the frame (it will pop up and you can interact with in - spawns a thread) 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.pack(); 
    frame.setVisible(true); 

    // Create a scanner so that you can get some input from the console (the easy way) 
    Scanner s = new Scanner(System.in); 

    for (int i = 0; i < fields.length; i++) { 

     // get the field you want to update 
     final JTextField field = fields[i]; 

     // get the input from the console 
     final String line = s.nextLine(); 

     // update the field (must be done thread-safe, therefore this construct) 
     SwingUtilities.invokeAndWait(new Runnable() { 
      @Override public void run() { field.setText(line); } 
     }); 
    } 
} 
+0

問題是我不知道那是什麼(3個月程序員):S ... – user1396316

+0

添加了解釋和更新代碼與評論。 – dacwe