如何在用户输入后立即打印JTextField值?

时间:2013-12-09 23:22:13

标签: java textfield changelistener

我希望用户在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

2 个答案:

答案 0 :(得分: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);
}
}

答案 1 :(得分: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());