简体   繁体   中英

sharing variables between JPanel classes in java

I am new to Java and I am really struggling with this for my class. I need to declare

      student st1 = new student ("Grant", "Kline", 21);

once, and let two different classes use it. I can make it work by adding that line into each class, but the assignment doesn't allow that. st1.getInfo() and st1.whatsUp() will return the correct information when I have

      student st1 = new student ("Grant", "Kline", 21);

in CenterPanel and TopPanel.

Here are all my classes

public class  app
{
  public static void main(String args[]) 
{

myJFrame mjf = new myJFrame();

 }
}

public class myJFrame extends JFrame
{
    public myJFrame ()
    {
        super ("My First Frame");
        ControlJPanel mjp = new ControlJPanel();
        getContentPane().add(mjp,"Center");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize (800, 480);
        setVisible(true);
    }
}
public class ControlJPanel extends JPanel
{
 public ControlJPanel ()
 {

   super ();
   setLayout(new BorderLayout());
   CenterPanel centerP = new CenterPanel();
   TopPanel topP = new TopPanel();
   add(topP, "North");
   add(centerP, "Center");

}
}
public class TopPanel extends JPanel
{
  public TopPanel ()
   {
        super ();
        setBackground(Color.yellow);
        JButton jb1 = new JButton(st1.getInfo());
        add(jb1);
   }
}
public CenterPanel ()
   {
    super ();
    GridLayout grid = new GridLayout(0,1);
    setLayout(grid);

    JButton jb2 = new JButton(st1.whatsUp());
    add(jb2);

    JButton jb3 = new JButton(st1.whatsUp());
    add(jb3);        

    JButton jb4 = new JButton(st1.whatsUp());
    add(jb4);

    JButton jb5 = new JButton(st1.whatsUp());
    add(jb5);

    JButton jb6 = new JButton(st1.whatsUp());
    add(jb6);

    JButton jb7 = new JButton(st1.whatsUp());
    add(jb7);

    JButton jb8 = new JButton(st1.whatsUp());
    add(jb8);

    JButton jb9 = new JButton(st1.whatsUp());
    add(jb9);

    JButton jb10 = new JButton(st1.whatsUp());
    add(jb10);

    JButton jb11 = new JButton(st1.whatsUp());
    add(jb11);
   }
}

I also have a student class which I cannot add code to.

You need to create class attributes eg

public class TopPanel extends JPanel
{
  private Student std = null; 
  public TopPanel ()
   {
 //... code
  public void setStudent(Student std) {
    this.std = std;
  }

and then when creating TopPanel

Student st1 = new Student ("Grant", "Kline", 21);
TopPanel tp = new TopPanel();
tp.setStudent(st1);

CenterPanel cp = new CenterPanel();
cp.setStudent(st1);

In such way you pass the reference of one Student object to two differetn Panel objects

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