javaswingdesktop-applicationbeans-binding

How to bind a JProgressbar to a Bean class's property


Any one can give a sample code or a link how to bind a JProgressbar to a bean class'property in Swing applications?


Solution

  • You could use JGoodies Binding to bind the progress bar to your model. But your (view-)model must fire property change events for this to work. http://www.jgoodies.com/downloads/libraries.html I can post an example code on monday.

    Example:

    In your ViewModel:

    private final PropertyChangeSupport changeSupport = new PropertyChangeSupport(this);
    
    private int progress;
    
    public void addPropertyChangeListener(PropertyChangeListener listener)
    {
        changeSupport.addPropertyChangeListener(listener);
    }
    
    public void removePropertyChangeListener(PropertyChangeListener listener)
    {
        changeSupport.removePropertyChangeListener(listener);
    }
    
    public int getProgress()
    {
        return progress;
    }
    
    public static final String PROPERTY_PROGRESS = "progress";
    
    public void setProgress(int progress)
    {
        int old = this.progress;
        this.progress = progress;
        changeSupport.firePropertyChange(PROPERTY_PROGRESS, old, progress);
    }
    

    In your View:

    BeanAdapter<ViewModel> beanAdapter = new BeanAdapter<ViewModel>(viewModel, true);
    Bindings.bind(progressBar, "value", beanAdapter.getValueModel(ViewModel.PROPERTY_PROGRESS));