Change size of JPanel using CardLayout

女生的网名这么多〃 提交于 2019-12-17 14:15:23

问题


is it possible to change the size of Jpanels when using Java CardLayout?


回答1:


shoot, something like this where the component (here a JLabel rather than a JPanel) has it's preferredSize set, then place it in another JPanel that uses an appropriate layout, here GridBagLayout which with default settings will center the component, and add the GridBagLayout using JPanel to the CardLayout using 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();
         }
      });
   }
}


来源:https://stackoverflow.com/questions/5414177/change-size-of-jpanel-using-cardlayout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!