从其他类访问Java Swing TextField

问题描述:

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

你可能不真的想要一个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

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

}