问题描述
在两个按钮之间切换时,您希望显示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 (将#修改为@)