我在完成家庭作业时遇到了很多麻烦。我们获得了三个JPanel:myJPanel,myJPanel1和myJPanel2。我必须在mJPanel1中有一个JButton,在myJPanel2中更新按钮b2的文本。问题是我无法对myJPanel2进行任何更改。我尝试的一切都给了我一个NullPointerException。请帮忙。
这是代码: myJPanel -
import java.awt.*;
import javax.swing.*;
public class MyJPanel extends JPanel {
MyJPanel panel;
public MyJPanel() {
super();
setBackground(Color.gray);
setLayout(new BorderLayout());
MyJPanel2 p2 = new MyJPanel2();
add(p2, "Center");
MyJPanel1 p1 = new MyJPanel1(p2);
add(p1, "North");
}
}
myJPanel1 -
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class MyJPanel1 extends JPanel implements ActionListener {
JButton jl1;
Student st1 = new Student("Fred", "Fonseca", 44);
myJPanel panel;
myJPanel2 panel2;
public MyJPanel1(JPanel p2) {
super();
setBackground(Color.yellow);
// the whatsUp of this student has to shown in the other panel
jl1 = new JButton(st1.getInfo());
jl1.addActionListener(this);
add(jl1);
}@
Override
public void actionPerformed(ActionEvent event) {
Object obj = event.getSource();
if (obj.equals(jl1)) {
panel2.b2.setText("test"); //This is where the NullPointerException is...
}
}
}
myJPanel2 -
import java.awt.*;
import javax.swing.*;
public class myJPanel2 extends JPanel {
//==================================================
//no changes allowed in myJPanel2 for assignment 05
//==================================================
JButton b1, b2, b3, b4;
public myJPanel2() {
super();
setBackground(Color.pink);
//setLayout(new GridLayout(3,1));
b1 = new JButton("When the user clicks on the button in the UPPER panel");
add(b1);
b2 = new JButton("Display here whatsUp from the student in UPPER Panel");
add(b2);
b3 = new JButton("===>>>>You CANNOT create a student here <======");
add(b3);
b4 = new JButton("It has to be the student from the UPPER Panel");
add(b4);
}
}
非常感谢任何帮助。几天来我一直坚持这个问题。