I have a Java class and I want one of its properties to be displayed by a JLabel in a Swing desktop application:
class Item {
private String name;
private Integer quantity;
// getters, setters...
}
class Frame {
Item item = new Item();
...
JLabel label = new JLabel();
label.setText(item.getQuantity().toString());
...
}
How do I get the label to update its text whenever the quantity property changes on the item?
Something will have to update the text of your label (with the setText
method you already know). Probably the easiest thing is to let the Item
class fire PropertyChangeEvent
s when its properties are changed, and attach a listener to the item which updates the label.
final JLabel label = new JLabel();
label.setText(item.getQuantity().toString());
item.addPropertyChangeListener( new PropertyChangeListener(){
@Override
public void propertyChange( PropertyChangeEvent event ){
if ( "quantity".equals( event.getPropertyName ) ){
//I assume this happens on the EDT, otherwise use SwingUtilities.invoke*
label.setText( (String)event.getNewValue() );
}
}
});
The PropertyChangeSupport
class makes it easy to manage the listeners and fire the events in your Item
class