Giovanni
Giovanni

Reputation: 91

JLabel on change text event

How I can retrive the event on a JLabel when change the text inside??

I have a JLabel and when change the text inside I have to update other field.

Upvotes: 9

Views: 11403

Answers (2)

kleopatra
kleopatra

Reputation: 51525

techically, the answer is to use a PropertyChangeListener and listen to changes of the "text" property, something like

 PropertyChangeListener l = new PropertyChangeListener() {
       public void propertyChanged(PropertyChangeEvent e) {
           // do stuff here
       }
 };
 label.addPropertyChangeListener("text", l);

not so technically: could be worth to re-visit the overall design and bind to original source which triggered the change in the label

Upvotes: 12

Erik
Erik

Reputation: 3777

IMHO you can not get an event on JLabels textchange. But you can use a JTextField instead of a JLabel:

private JTextField textFieldLabel = new JTextField();
textFieldLabel.setEditable(false);
textFieldLabel.setOpaque(true);
textFieldLabel.setBorder(null);

textFieldLabel.getDocument().addDocumentListener(new DocumentListener() {

    public void removeUpdate(DocumentEvent e) {
        System.out.println("removeUpdate");
    }

    public void insertUpdate(DocumentEvent e) {
        System.out.println("insertUpdate");
    }

    public void changedUpdate(DocumentEvent e) {
        System.out.println("changedUpdate");
    }
});

Note: this event is fired no matter how the text gets changed; programatically via "setText()" on the TextField or (if you do not "setEditable(false)") via clipboard cut/paste, or by the user typing directly into the field on the UI.

The lines:

textFieldLabel.setEditable(false);
textFieldLabel.setOpaque(true);
textFieldLabel.setBorder(null);

are used to make the JTextField look like an JLabel.

Upvotes: 2

Related Questions