Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
318 views
in Technique[技术] by (71.8m points)

java - Change size of JPanel using CardLayout

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();
         }
      });
   }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...