簡體   English   中英

從其他類訪問Java Swing TextField

[英]Access to Java Swing TextField from other class

我有Java Swing文本輸入的問題。 我在類A有一個方法inputData() ,當我調用它時,該方法應該等待用戶在類B填充TextField input並按Enter。 最后, inputData()方法應該包含用戶編寫的文本。 我該怎么解決?

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

文本域? 既然它是一個Swing項目,我希望你的意思是一個JTextField,對吧? 並且不要向它添加KeyListener,而是添加ActionListener,因為當用戶按Enter鍵時會觸發它們。 解決問題的一種方法是為GUI類(此處命名為B)提供一個公共方法,該方法允許外部類將ActionListener添加到JTextField。 也許你可以將其稱為addActionListenerToInput(ActionListener listener)。 然后,A類可以將偵聽器添加到B,並且在按下enter時將調用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);
   }

}

您可能實際上並不想要JTextField。 聽起來你正在等待來自用戶的一行輸入,這應該是一個JOptionPane。 這里描述了如何做到這一點:

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

基本上,JOptionPane.showInputDialog()將彈出一個窗口,其中包含一個文本字段和OK / Cancel按鈕,如果按Enter鍵,它將接受您的輸入。 這消除了對另一個類的需要。

你把它放在你的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)
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM