gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 14:23:46 25 4
gpt4 key购买 nike

我有两个 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

...
}

最佳答案

使用卡片布局。 (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);

关于java - 在 JPanel 之间切换(隐藏/显示),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26894385/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com