gpt4 book ai didi

java - JFrame 的卡片布局?

转载 作者:行者123 更新时间:2023-12-01 21:52:14 25 4
gpt4 key购买 nike

我一直在四处寻找,包括在 Java 文档中,但没有找到我的问题的明确答案:我想通过单击按钮从一个 JFrame 切换到另一个 JFrame;也就是说,关闭旧的 JFrame,同时打开新的 JFrame。我听说过“CardLayout”,但我不太确定它是如何工作的。有人介意解释一下吗,或者其他方法吗?

谢谢

最佳答案

这是 CardLayout 的示例

正如您听过其他人所说,don't use multiple JFrames.

import javax.swing.*;
import java.awt.*;

public class MainFrame
{
static JPanel homeContainer;
static JPanel homePanel;
static JPanel otherPanel;
static CardLayout cl;

public MainFrame()
{
JFrame mFrame = new JFrame("CardLayout Example");
JButton showOtherPanelBtn = new JButton("Show Other Panel");
JButton backToHomeBtn = new JButton("Show Home Panel");

cl = new CardLayout(5, 5);
homeContainer = new JPanel(cl);
homeContainer.setBackground(Color.black);

homePanel = new JPanel();
homePanel.setBackground(Color.blue);
homePanel.add(showOtherPanelBtn);

homeContainer.add(homePanel, "Home");

otherPanel = new JPanel();
otherPanel.setBackground(Color.green);
otherPanel.add(backToHomeBtn);

homeContainer.add(otherPanel, "Other Panel");

showOtherPanelBtn.addActionListener(e -> cl.show(homeContainer, "Other Panel"));
backToHomeBtn.addActionListener(e -> cl.show(homeContainer, "Home"));

mFrame.add(homeContainer);
cl.show(homeContainer, "Home");
mFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
mFrame.setLocationRelativeTo(null);
mFrame.setExtendedState(JFrame.MAXIMIZED_BOTH);
mFrame.pack();
mFrame.setVisible(true);
}

public static void main(String[] args)
{
SwingUtilities.invokeLater(MainFrame::new);
}
}

关于java - JFrame 的卡片布局?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35004701/

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