简体   繁体   中英

Update JLabel when custom object property changes

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

通过调用Component附带的repaint()。

我可能会向您的Item对象添加一个ObjectChangeListener,然后重写它的objectChanged方法以更新JLabel并调用repaint()。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM