9

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.

2
  • 1
    Would it be better to update both fields at once, from whatever event caused the first to change? Commented Oct 15, 2010 at 23:11
  • I put a text i jlabel1 with click on a button and depending on what i have chose I have to put another text i a jLabel2 Commented Oct 15, 2010 at 23:22

2 Answers 2

12

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

Sign up to request clarification or add additional context in comments.

Comments

2

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.

1 Comment

this answer is wrong (the part related to available listeners for JLabel)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.