JAVA JFrame切换JPanel

2025-01-03 18:48:34
推荐回答(3个)
回答1:

声明3个JPanel:p1,p2,p3
public class P3 extends JPanel
{
private JPanel p1;
private JPanle p2;
private CardLayout out;

public P3()
{
out = new CardLayout();
setLayout(out);
p1 = new P1(this);
p2 = new P2(this);

add("p1", p1);
add("p2", p2);
}

public void setCurrentPanel(String panelName)
{
out.show(this, panelName);
}

}

public class P1 extends JPanel implements Runnable
{
private P3 p3;
private int i = 0;

public P1(P3 p3)
{
this.p3 = p3;
}

public void run()
{
while (true)
{
if (i == 1)
{
p3.setCurrentPanel("p2");
}
}
}
}

p2的声明我就不写了哈,只是说明一种方法,往p2里面传p3的对象只是方便你返回到p1,如果没有返回的必要,就不用传了。

回答2:

你可以先把p2.setVisible(false).if(i===1){
p1.setVisible(false);
p2.setVisible(true);
}

回答3:

在线程中判断 if(xxx){
JFrame.removeAll;

JFrame.repaint();

JFrame.add(JPanel);

}