gpt4 book ai didi

java - 使用 CardLayout 更改 JPanel 的大小

转载 作者:行者123 更新时间:2023-12-04 06:31:04 25 4
gpt4 key购买 nike

使用 Java CardLayout 时是否可以更改 Jpanels 的大小?

最佳答案

拍摄,像这样,其中组件(这里是 JLabel 而不是 JPanel)设置了首选大小,然后将其放置在另一个使用适当布局的 JPanel 中,这里使用默认设置的 GridBagLayout 将使组件居中,并使用添加 GridBagLayout JPanel 到 CardLayout 使用 panel::

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.Border;

public class MultiSizedPanels {

private static void createAndShowUI() {
final CardLayout cardLayout = new CardLayout();
final JPanel cardHolder = new JPanel(cardLayout);

JLabel[] labels = {
new JLabel("Small Label", SwingConstants.CENTER),
new JLabel("Medium Label", SwingConstants.CENTER),
new JLabel("Large Label", SwingConstants.CENTER)};

for (int i = 0; i < labels.length; i++) {
int padding = 50;
Dimension size = labels[i].getPreferredSize();
size = new Dimension(size.width + 2 * (i + 1) * padding, size.height + 2 * (i + 1) * padding);
labels[i].setPreferredSize(size);
Border lineBorder = BorderFactory.createLineBorder(Color.blue);
labels[i].setBorder(lineBorder);
JPanel containerPanel = new JPanel(new GridBagLayout());
containerPanel.add(labels[i]);
cardHolder.add(containerPanel, String.valueOf(i));
}

JButton nextButton = new JButton("Next");
nextButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cardLayout.next(cardHolder);
}
});
JPanel btnHolder = new JPanel();
btnHolder.add(nextButton);

JFrame frame = new JFrame("MultiSizedPanels");
frame.getContentPane().add(cardHolder, BorderLayout.CENTER);
frame.getContentPane().add(btnHolder, BorderLayout.SOUTH);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}

public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}

关于java - 使用 CardLayout 更改 JPanel 的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5414177/

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