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 theItem
class firePropertyChangeEvent
s when its properties are changed, and attach a listener to the item which updates the label.The
PropertyChangeSupport
class makes it easy to manage the listeners and fire the events in yourItem
class