[英]sharing variables between JPanel classes in java
I am new to Java and I am really struggling with this for my class. 我是Java的新手,我在课堂上确实为此感到挣扎。 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
当我有st1.getInfo()和st1.whatsUp()将返回正确的信息
student st1 = new student ("Grant", "Kline", 21);
in CenterPanel and TopPanel. 在CenterPanel和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 然后在创建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 这样,您可以将一个“学生”对象的引用传递给两个不同的“面板”对象
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.