If you try changing this line:
new TestPanel2().panel2.removeAll();
To:
new TestPanel2().panel2().removeAll();
Will solve the problem, but the current logic is flawed.
A better solution is:
Change TestPanel2
to:
public class TestPanel2 {
JPanel panel2;
JList jlist;
String[] list = { "Sachin", "Tarun", "Vipin" };
public TestPanel2() { // was: JPanel panel2() {
panel2 = new JPanel();
jlist = new JList(list);
panel2.add(jlist);
panel2.add(new JLabel("Test"));
// was: return panel2;
}
}
And then modify TestPanel1
to:
public class TestPanel1 {
JPanel panel1;
JButton next;
public TestPanel1(final JFrame frame, TestPanel2 tp2) { // was: JPanel panel1() {
panel1 = new JPanel();
next = new JButton("Next");
final JPanel panel2 = tp2.panel2; // line created
next.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
panel2.removeAll(); // was: new TestPanel2().panel2.removeAll();
frame.validate(); // line created
frame.paint(); // line created
}
});
panel1.add(next);
// was: return panel1;
}
}
Finally, on PanelEventTest.originalFrame()
, change:
frame.add(new TestPanel1().panel1());
frame.add(new TestPanel2().panel2());
to:
TestPanel2 tp2 = new TestPanel2();
frame.add(new TestPanel1(frame, tp2).panel1);
frame.add(tp2.panel2);
frame.validate();
frame.repaint();
Explanation
You are creating methods, when you needed constructors. You must read this: Understanding constructors.
Also, you need to pass TestPanel2
and the frame
to TestPanel1
:
- Your code was creating a new
TestPanel2
(attached to no one) and then calling removeAll()
on it's pannel. This has no effect at all (as this panel is not shown anywhere).
- The changed then code will call
removeAll()
on TestPanel1
's panel.
- Also, you need to revalidate/repaint the components everytime you make a change on them.
- Currently you change them when you create the
frame
(adding the panels) and when you remove the panel2
(in the "Next" button's action).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…