2011-03-12 82 views
3

我有Java Swing文本輸入的問題。我在類A中有一個方法inputData(),當我調用它時,該方法應該等待用戶填寫類B中的TextField input,然後按ENTER鍵。最後,方法inputData()應該有用戶編寫的文本。我怎麼解決它?從其他類訪問Java Swing TextField

class A { 
    B b = new B(); 
    public A() { 
     inputData(); 
    } 

    public char[] inputData() { 
     // there I would like to get text 
     // from TextField from class B 
    } 
} 

//------------------------------- 

class B extends JFrame{ 
    private JTexField input; 

    public B() { 
    } 

    private void inputKeyPressed(KeyEvent e) {         
     if (e.getKeyCode() == 10) { // pressed ENTER 
      input.getText() 
      input.setText(null); 
     } 
    } 
} 

回答

3

你可能不真的想要一個JTextField。這聽起來像你在等待用戶輸入的一行,這應該是一個JOptionPane。如何做到這一點的描述如下:

http://download.oracle.com/javase/tutorial/uiswing/components/dialog.html#input

基本上,JOptionPane.showInputDialog()將導致一個窗口彈出包含一個文本字段和確定/取消按鈕,如果按輸入將採取你的意見。這消除了另一個班的需要。

你最好把它放在你的inputData()方法:

inputData() 
{ 
    String input = JOptionPane.showInputDialog(...); 
    //input is whatever the user inputted 
} 

如果這就是你要找不是爲和你想的是保持開放的文本字段,也許你真正想要的是一個「提交「按鈕旁邊的JTextField,允許用戶決定何時提交文本。在這種情況下,您可以有:

class B extends JFrame 
{ 
    private A myA; 

    private JTextField input; 

    private JButton submitButton; 

    public B() 
    { 
     submitButton.addActionListener(new SubmitListener()); 
    } 

    private class SubmitListener 
    { 
     //this method is called every time the submitButton is clicked 
     public void actionPerformed(ActionEvent ae) 
     { 
      myA.sendInput(inputField.getText()); 
      //A will need a method sendInput(String) 
     } 
    } 
} 
+0

關於JOptionPane(1+)的好處。 JDialog將是另一個類似的選擇。 – 2011-03-12 21:46:04

3

TextField?由於這是一個Swing項目,我希望你的意思是一個JTextField,對吧?並且不要向它添加KeyListener,而是添加一個ActionListener,因爲當用戶按下Enter時會觸發它們。解決問題的一種方法是給GUI類(這裏命名爲B)提供一個公共方法,允許外部類將ActionListener添加到JTextField。也許你可以稱之爲addActionListenerToInput(ActionListener監聽器)。然後,類A可以將偵聽器添加到B中,並且當按下回車時,actionPerformed代碼將被調用。

例如,

class A { 
    B b = new B(); 
    public A() { 
     //inputData(); 
     b.addActionListenerToInput(new ActionListener() { 
     public void actionPerformed(ActionEvent e) { 
      inputActionPerformed(e); 
     } 
     }); 
    } 

    private void inputActionPerformed(ActionEvent e) { 
     JTextField input = (JTextField) e.getSource(); 
     String text = input.getText(); 
     input.setText(""); 

     // do what you want with the text String here 
    } 
} 

//------------------------------- 

class B extends JFrame{ 
    private JTextField input; 

    public B() { 
    } 

    public void addActionListenerToInput(ActionListener listener) { 
     input.addActionListener(listener); 
    } 

}