質問

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 PropertyChangeEvents 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

他のヒント

By calling repaint() which is inhereted from Component.

I'd probably add an ObjectChangeListener to your Item object, then override it's objectChanged method to update the JLabel and call repaint().

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top