1 回答
TA贡献1856条经验 获得超11个赞
问题是您不断创建JPanel. remove如果JPanel您JToggleButton未被选中,您可以添加一个已创建的实例JPanel,如果按钮被选中。看这个简单的例子:
public class MainFrame extends JFrame {
private JPanel topPanel = new JPanel();
private JPanel centerPanel = new JPanel();
private JToggleButton toggleButton = new JToggleButton("Toggle");
public MainFrame() {
this.setVisible(true);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setLayout(new BorderLayout());
this.topPanel.setPreferredSize(new Dimension(100, 100));
this.centerPanel.setPreferredSize(new Dimension(100, 100));
this.toggleButton.setPreferredSize(new Dimension(100, 100));
this.add(topPanel, BorderLayout.NORTH);
this.add(centerPanel, BorderLayout.CENTER);
this.add(toggleButton, BorderLayout.SOUTH);
this.toggleButton.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if(e.getStateChange() == ItemEvent.SELECTED) {
add(centerPanel, BorderLayout.CENTER);
} else {
remove(centerPanel);
}
pack();
}
});
this.pack();
this.setVisible(true);
}
}
你可以看到它只centerPanel被实例化了一次。
添加回答
举报