gpt4 book ai didi

java - 如何实现这个功能呢?

转载 作者:行者123 更新时间:2023-12-02 04:07:52 25 4
gpt4 key购买 nike

我有一个 JPanel 对象(例如 panel),它保存对 JPanel 对象的引用。假设 panel 指向 panel-1,并且在某些单击(操作)时,它应该指向 panel-2,并且 panel-2 必须替换 JFrame 对象框架上的 panel-1。

但是,它没有更新。我尝试了以下方法,但没有成功:

frame.repaint();
panel.revalidate();

最佳答案

我认为这段代码可以实现您想要做的事情。它有一个 JPanel,可以容纳一个绿色 JPanel 或一个红色 JPanel 以及一个用于进行翻转的按钮。

public class Test{
boolean isGreen; // flag that indicates the content

public Test(){
JFrame f = new JFrame ("Test"); // the Frame
f.setLayout (new BorderLayout());

JPanel p = new JPanel(new BorderLayout()); // the content Panel
f.add(p, BorderLayout.CENTER);

JPanel green = new JPanel(); // the green content
green.setBackground(Color.GREEN);

JPanel red = new JPanel(); // the red content
red.setBackground(Color.RED);

p.add(green); // init with green content
isGreen = true;

JButton b = new JButton ("flip"); // the flip button
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
p.removeAll(); // remove all of old content
if(isGreen){
p.add(red); // set new red content
isGreen = false;
} else {
p.add(green); // set new green content
isGreen = true;
}
p.revalidate(); // invalidate content panel so component tree will be reconstructed
f.repaint(); // repaint the frame so the content change will be seen
}
});
f.add (b, BorderLayout.SOUTH);
f.pack();
f.setSize(250,330);
f.setVisible (true);
}
public static void main (String [] args){
new Test();
}
}

关于java - 如何实现这个功能呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34084199/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com