Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 379
Giovanni Avatar asked Oct 15 '10 23:10

Giovanni


People also ask

How do you text wrap a JLabel?

As per @darren's answer, you simply need to wrap the string with <html> and </html> tags: myLabel. setText("<html>"+ myString +"</html>"); You do not need to hard-code any break tags.

Is JLabel editable?

It is impossible to make an editable label as it exists. You can use a jTextField with no border and same background as the JFrame. Having said that, you can add a KeyListener to your JLabel and update your label's text depending on the key that was pressed.


2 Answers

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

like image 138
kleopatra Avatar answered Oct 04 '22 20:10

kleopatra


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.

like image 24
Erik Avatar answered Oct 04 '22 20:10

Erik