Dan
Dan

Reputation: 1813

How to access a child object from parent component (JFrame)

I have a top level container (JFrame) that contains two JPanels. One of the JPanel children has a property that will change and that needs to trigger an update on one of the other JPanel components (a JProgressBar).

How can I access this component from the JPanel where the property change is triggered? If this is not the correct way to do it, is there any other method to propagate the property change to it?

Upvotes: 2

Views: 4459

Answers (1)

Vincent Ramdhanie
Vincent Ramdhanie

Reputation: 103145

Sounds like you need to use an Observer of some sort. Here is a simple example of having the JFrame become aware of property changes in the panel and then updating the other panel accordingly. If your design gets complex and you have many different components that must become aware of changes in each other then you should consider the mediator pattern.

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
 import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;


public class ObserverFrame extends JFrame {

  Panel1 panel;
  JPanel panel2;
  JLabel label;

 //to kick off the example
public static void main(String args[]){
    new ObserverFrame();        
}

//constructor of the JFrame
public ObserverFrame(){
    super("Observer Example");

    //the panel that we want to observe
    //notice that we pass a reference to the parent
    panel = new Panel1(this);
    add(panel, BorderLayout.NORTH);

    //another panel to be updated when the property changes
    panel2 = new JPanel();
    label = new JLabel("Panel to be updated");

    panel2.add(label);

    add(panel2, BorderLayout.SOUTH);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setSize(500, 500);
    setVisible(true);
}

//this method will be called by the panel when the property changes.
public void trigger(Panel1 panel) {
    label.setText(String.valueOf(panel.getProperty()));
}


//inner class for convenience of the example
class Panel1 extends JPanel{
    ObserverFrame parent;
    JButton b1;
    private int property;

    //accept the parent
    public Panel1(ObserverFrame p){
        this.parent = p;
        b1 = new JButton("Click Me");
        //click the button to change the property
        b1.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
                setProperty(getProperty() * 2); //update property here
            }
        });
        property = 10;
        add(b1);
    }

    //the property that we care about
    public int getProperty() {
        return property;
    }

    //when the setter is called, trigger the parent
    public void setProperty(int property) {
        this.property = property;
        parent.trigger(this);
    }


  }

}

Upvotes: 3

Related Questions