我有两个相互叠加的JPanel。 “顶部”面板包含许多小部件(JButtons,JTextFields等)。其中一个按钮将启动一个动作以显示许多图像。
这些图像显示在另一张JPanel上。因此,单击此按钮时,我想隐藏控制面板并显示图像面板。听起来很简单。
这是代码(我省略了许多我认为不相关的东西)。在构造函数中,如果我在应用程序启动时切换哪个面板是可见的,那么它看起来很好。当我点击按钮时,我应该从深灰色控制面板转到蓝色图像面板。除了发生的事情是我的深灰色控制面板变成一个空的白色面板。有什么想法吗?
public GUI() {
JFrame frame = new JFrame();
...
JPanel imagesPanel = new ImagesPanel();
imagesPanel.setBackground(Color.BLUE);
imagesPanel.setVisible(false);
frame.getContentPane().add(imagesPanel, BorderLayout.CENTER);
// make a JPanel to hold all of the buttons and text fields
JPanel imagesPanel = new ImagesPanel();
controlPanel.setBackground(Color.DARK_GRAY);
controlPanel.setVisible(true);
frame.getContentPane().add(controlPanel, BorderLayout.CENTER);
...
JButton btnDisplayImages = new JButton("Display Images");
btnDisplayImages.setPreferredSize(standardButtonSize);
btnDisplayImages.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
imagesPanel.setVisible(true);
controlPanel.setVisible(false);
frame.repaint();
frame.setVisible(true);
}
});
// button added to control panel
...
}
答案 0 :(得分:0)
使用CardLayout。 (docs.oracle.com/javase/tutorial/uiswing/layout/card.html)
final String IMAGES_PANEL = "Images Panel";
final String CONTROL_PANEL = "Control Panel";
CardLayout cardLayout;
JPanel cards;
//Where the components controlled by the CardLayout are initialized:
//Create the "cards".
JPanel card1 = new JPanel();
...
JPanel card2 = new JPanel();
...
//Create the panel that contains the "cards".
cardLayout = new CardLayout();
cards = new JPanel(cardLayout);
cards.add(card1, IMAGES_PANEL);
cards.add(card2, CONTROL_PANEL);
...
//Show images panel
cardLayout.show(cards,IMAGES_PANEL);
...
//Show control panel
cardLayout.show(cards, CONTROL_PANEL);