我是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);
}
}
我还有一个学生班,我无法添加代码。
答案 0 :(得分:0)
您需要创建类属性,例如
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对象