如何解决如何在 CardLayout 中使用相同的面板?
在两个按钮之间切换时,您希望显示ItemJpanel.getInstance()
。但只有切换到第二个按钮时才会生效。
public class TestCardLayout extends JFrame implements ActionListener {
JButton b0,b1;
Panel cardPanel = new Panel();
Panel controlPanel = new Panel();
CardLayout card = new CardLayout();
Item items[] = {new Item("aaa"),new Item("bbb")};
public TestCardLayout() {
setSize(400,200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
cardPanel.setLayout(card);
for (int i = 0; i < 2; i++) {
cardPanel.add(items[i].name,items[i].propertyPanel);
}
b0 = new JButton("0");
b1 = new JButton("1");
b0.addActionListener(this);
b1.addActionListener(this);
controlPanel.add(b0);
controlPanel.add(b1);
Container container = getContentPane();
container.add(cardPanel,BorderLayout.CENTER);
container.add(controlPanel,BorderLayout.SOUTH);
}
public void actionPerformed(ActionEvent e) {
int i = 0;
if (e.getSource() == b0) {
i = 0;
}
if (e.getSource() == b1) {
i = 1;
}
card.show(cardPanel,items[i].name);
}
public static void main(String[] args) {
TestCardLayout testCardLayout = new TestCardLayout();
testCardLayout.setVisible(true);
}
}
class Item {
String name;
public JComponent propertyPanel;
private JComponent contentPane;
Item(String name) {
this.name = name;
initPropertyPanel();
}
private void initPropertyPanel() {
contentPane = ItemJPanel.getInstance();
propertyPanel = new JPanel();
propertyPanel.setBackground(Color.pink);
propertyPanel.add(contentPane,BorderLayout.CENTER);
}
}
class ItemJPanel extends JPanel {
static ItemJPanel itemJPanel = new ItemJPanel();
ItemJPanel() {
JButton jButton = new JButton("hhhhh");
this.add(jButton);
}
public static ItemJPanel getInstance() {
return itemJPanel;
}
}
当我将 initPropertyPanel()
替换为以下按钮时,切换到第一个按钮也将起作用。
propertyPanel = ItemJPanel.getInstance();
我想知道为什么第一个示例不起作用。是不是忘记调用刷新函数了?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。