2013-12-09 59 views
1

我希望用戶在JTextField中輸入一個值,並使用監聽器來聆聽文本字段,並在不按任何鍵的情況下直接將值打印到控制檯。如何在用戶輸入後立即打印JTextField值?

textfield1.addChangeListener(new ChangeListener() { 
    public void actionPerformed(ActionEvent e) {     
     System.out.println(textfield1); 
    } 
}); 

錯誤:

<anonymous textfield$2> is not abstract and does not override abstract method stateChanged(ChangeEvent) in ChangeListener 
+0

的可能重複http://stackoverflow.com/questions/3953208/value-change-listener-to- jtextfield – maheeka

+0

Iam在談論ChangeListener而不是documentlistener。你可以幫我嗎? – user2994263

+0

我不認爲你會,但如果你對我告訴你放置代碼的位置感到困惑,請評論我的回答。雖然這很容易,你可能會得到它。 –

回答

2

將這個私有類你的公共類。就像一種方法。

private class textChangedListener implements KeyListener 
{ 
    public void keyPressed(KeyEvent e){} 
    public void keyReleased(KeyEvent e){} 

    public void keyTyped(KeyEvent e) 
    { 
     System.out.print(textField1.getText()); 
    } 
} 

然後在你的主要方法是打電話給你的JTextField像這樣:

private JTextField textField1; // just showing the name of the JTextField 
textField1.addKeyListener(new textChangedListener()); 
3

是,只要使用的KeyListener類,見下面的例子:

import javax.swing.*; 
import java.awt.*; 
import java.awt.event.KeyAdapter; 
import java.awt.event.KeyEvent; 

public class Main extends JFrame { 
    public Main() throws HeadlessException { 
    setSize(200, 200); 
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    setLayout(new FlowLayout(FlowLayout.LEFT)); 

    JLabel label = new JLabel("Write something: "); 
    JTextField input = new JTextField(); 

    input.setPreferredSize(new Dimension(100, 20)); 

    final JTextField output = new JTextField(); 
    output.setPreferredSize(new Dimension(100, 20)); 
    add(label); 
    add(input); 
    add(output); 

    input.addKeyListener(new KeyAdapter() { 
     public void keyReleased(KeyEvent e) { 
      JTextField textField = (JTextField) e.getSource(); 
      String text = textField.getText(); 
      output.setText(text); 
     } 

     public void keyTyped(KeyEvent e) { 

     } 

     public void keyPressed(KeyEvent e) { 
     } 
    }); 
} 

public static void main(String[] args) { 
    new Main().setVisible(true); 
} 
}