简体   繁体   English

在JPanel之间切换(隐藏/显示)

[英]Toggling between JPanels (hide/show)

I have two JPanels that sit on top of one another. 我有两个JPanels彼此重叠。 The 'top' panel holds many widgets (JButtons, JTextFields, etc.). “顶部”面板包含许多小部件(JButton,JTextField等)。 One of the buttons will initiate an action to display a number of images. 其中一个按钮将启动一项操作,以显示许多图像。

These images are displayed on the other JPanel. 这些图像显示在另一个JPanel上。 So, when this button is clicked, I want to hide the control panel and display the images panel. 因此,当单击此按钮时,我想隐藏控制面板并显示图像面板。 Sounds pretty simple. 听起来很简单。

Here is the code (I've omitted a lot of stuff that I don't think is relevant). 这是代码(我省略了很多我认为不相关的内容)。 In the constructor, if I switch which panel is visible when the app launches, it looks fine either way. 在构造函数中,如果我在应用启动时切换了哪个面板可见,则无论哪种方式看起来都很好。 When I click the button, I should go from my dark gray control panel to my blue images panel. 单击按钮时,应该从深灰色控制面板转到蓝色图像面板。 Except that what happens is my dark gray control panel becomes an empty white panel. 除了发生什么,我的深灰色控制面板变成了空白面板。 Any ideas? 有任何想法吗?

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

    ...
}

Use CardLayout. 使用CardLayout。 (docs.oracle.com/javase/tutorial/uiswing/layout/card.html) (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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM