gpt4 book ai didi

java - CardLayout 中有 2 个以上可见的 JPanel

转载 作者:行者123 更新时间:2023-12-01 16:57:27 24 4
gpt4 key购买 nike

我在 CardLayout 中放置两个以上同时可见的 JPanel 对象时遇到问题。虽然我可以放置多个面板,但它们不会同时出现,并且我无法根据需要调整它们的大小。为了更清楚地了解我想要的内容,我添加了一张测试图像。

What I need to DO

最佳答案

在这种情况下,您可以将面板与BorderLayout一起使用作为常量和卡片的容器,然后是带有 CardLayout 的卡片(JPanel) 。这是一个简单的例子:

import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class TestFrame extends JFrame {

public static void main(String... s) {
new TestFrame();
}

public TestFrame() {
init();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setLocationRelativeTo(null);
setVisible(true);
}


private void init() {
setLayout(new BorderLayout());

JLabel head = new JLabel("Header");
head.setBorder(BorderFactory.createLineBorder(Color.BLACK));

JLabel side = new JLabel("SideBar");
side.setBorder(BorderFactory.createLineBorder(Color.BLACK));

JPanel changable = getPanel();
changable.setBorder(BorderFactory.createLineBorder(Color.BLACK));

add(head,BorderLayout.NORTH);
add(side,BorderLayout.WEST);
add(changable,BorderLayout.CENTER);
}


private JPanel getPanel() {
final CardLayout cards = new CardLayout(5,5);
final JPanel p = new JPanel(cards);
p.add(new JLabel("1"), "1");
p.add(new JLabel("2"), "2");

p.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
super.mouseClicked(e);
cards.next(p);
}
});

return p;
}

}

enter image description here

关于java - CardLayout 中有 2 个以上可见的 JPanel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30703297/

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