我是Java的新手,我真的为我的班级而苦苦挣扎。我需要声明
student st1 = new student ("Grant", "Kline", 21);一次,让两个不同的类使用它。我可以通过将该行添加到每个类中来使其工作,但赋值不允许这样做。st1.getInfo()和st1.whatsUp()将返回正确的信息
student st1 = new student ("Grant", "Kline", 21);在CenterPanel和TopPanel中。
这是我所有的课程
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);
}
}我还有一个学生类,我不能向其中添加代码。
发布于 2016-09-25 05:10:03
您需要创建类属性,例如
public class TopPanel extends JPanel
{
private Student std = null;
public TopPanel ()
{
//... code
public void setStudent(Student std) {
this.std = std;
}然后在创建TopPanel时
Student st1 = new Student ("Grant", "Kline", 21);
TopPanel tp = new TopPanel();
tp.setStudent(st1);
CenterPanel cp = new CenterPanel();
cp.setStudent(st1);通过这种方式,您可以将一个Student对象的引用传递给两个不同的Panel对象
https://stackoverflow.com/questions/39680788
复制相似问题