I am having a lot of trouble with a homework assignment. We were given three JPanels: myJPanel, myJPanel1, and myJPanel2. I have to have a JButton in mJPanel1 update the text of a button, b2, in myJPanel2. The problem is I can't make any changes to myJPanel2. Everything I try gives me a NullPointerException. Please help.
Here is the code: 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);
}
}
Any help would be greatly appreciated. I have been stuck on this problem for days.