1 回答

TA貢獻(xiàn)1856條經(jīng)驗(yàn) 獲得超11個(gè)贊
問(wèn)題是您不斷創(chuàng)建JPanel. remove如果JPanel您JToggleButton未被選中,您可以添加一個(gè)已創(chuàng)建的實(shí)例JPanel,如果按鈕被選中??催@個(gè)簡(jiǎn)單的例子:
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被實(shí)例化了一次。
添加回答
舉報(bào)