Search code examples
javaclasshierarchy

How can I pass variables from one class to another in Java?


I am trying to pass variables from one class to another. I have 3 classes shown below.

public class OvalPanel extends JPanel {
//declare variables

public OvalPanel() {

//create panel here

ovalShape = new OvalShape();
ovalShape.setMyColor(255, 255, 255);

//set layout down here
}

Then I have OvalShape.java

public class OvalShape extends JPanel {

public OvalShape() {
    Dimension size = getPreferredSize();
    size.width = 300;
    size.height= 300;
    setPreferredSize(size);
    setBorder(BorderFactory.createLoweredSoftBevelBorder());
}

public void setMyColor(int r, int g, int b) {
    this.myColor = new Color(r,g,b);
}

public void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.setColor(myColor);
    g.fillOval(0,0,100,100);
}

And finally DetailsPanel.java where the r,g,b values are set

public class DetailsPanel extends JPanel {

//declare variables

public DetailsPanel() {
    Dimension size = getPreferredSize();
    size.width = 250;
    setPreferredSize(size);


    redSlider = new JSlider(SwingConstants.VERTICAL, 0, 255, 0);
    redSlider.addChangeListener(
            new ChangeListener() {
                @Override
                public void stateChanged(ChangeEvent e) {
                    red = redSlider.getValue();
                }
            }
    );

    //greenSlider

    //blueSlider

    //set layout
}

My question is how can I pass the variables red, green, blue from DetailsPanel into the method ovalShape.setMyColor()in OvalPanel?


Solution

  • I think you need to do it through the parent object to which all the panels are added. You should take a look at the mediator design pattern:

    • a set of objects communicate in well-defined but complex ways. The resulting interdependencies are unstructured and difficult to understand.

    By using the mediator pattern you reduce dependencies between the 3 classes you have. In a good object-oriented design, those 3 classes should not depend one on each other so you can remove or replace them if you have to, without breaking the rest of the code.