1

I have a JTextField and an JLabel; if an user types a special character, such as /, I want the JLabel to setVisible(true).

I want this to be done without the user pressing any button, but in "real-time" as the typing is done, for each new character that is inserted, a check will be done. How do I do something like this?

6
  • 2
    add a listener for Key events, or a ChangeHandler Commented Jan 2, 2016 at 16:03
  • 3
    Or use a DocumentListener on the JTextField's document Commented Jan 2, 2016 at 16:07
  • 1
    Yes, use a DocumentListener. It is the API designed for usage with Swing. Read the Section from the Swing tutorial on How to Write a DocumentListener for more information and examples. Commented Jan 2, 2016 at 16:16
  • @Stultuske As a general rule of thumb, KeyListener is a bad idea, but especially for text components Commented Jan 2, 2016 at 21:07
  • @MadProgrammer: I never stated it to be ideal, but still better than "I don't know". If someone can't find a single way to do it, unfortunately, the "bad" ways are easier to explain than the "best design" practices Commented Jan 3, 2016 at 11:58

1 Answer 1

2

Simple solution using DocumentListener:

import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

public class DemoFrame extends JFrame {

    JTextField tf;
    JLabel lbl;

    public DemoFrame() {
        tf = new JTextField(10);
        lbl = new JLabel("Test");
        tf.getDocument().addDocumentListener(new DemoDocumentListener());
        lbl.setVisible(false);

        this.setLayout(new FlowLayout(FlowLayout.LEFT));
        this.add(tf);
        this.add(lbl);

        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setSize(500, 100);
        this.setVisible(true);
    }

    public void checkForSpecialString() {
        if (tf.getText().contains("/")) {
            lbl.setVisible(true);
        } else {
            lbl.setVisible(false);
        }
    }

    class DemoDocumentListener implements DocumentListener {
        @Override
        public void insertUpdate(DocumentEvent e) {
            checkForSpecialString();
        }
        @Override
        public void removeUpdate(DocumentEvent e) {
            checkForSpecialString();
        }
        @Override
        public void changedUpdate(DocumentEvent e) {
            checkForSpecialString();
        }
    }

    public static void main(String[] args) {
        new DemoFrame();
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.