Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I set the size of individual panels in a CardLayout?

When I create my GUI I use a cardlayout to hold my different panels as I'm sure many know. This sets my screen to the width and height of my largest panel. This causes problems with the aesthetics of my first to screens, which are much smaller than SudokuPanel and CalkuroPanel.

I have tried setting the preferred size when I change to the larger screens, but to no avail.

Any help with links to good info or anything that will just generally help would be greatly appreciated :).

Please find my main class (where I draw the GUI) below:

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

public class puzzleGUI{
  private static JPanel screens;
  public static String username;
  static public void main (String[] args){
  JFrame puzzle = new JFrame ("Sudoku/Calkuro Pro");

  ...

  PuzzleStartPanel startPanel = new PuzzleStartPanel();
  PuzzleChoosePanel choosePanel = new PuzzleChoosePanel();
  PuzzleSudokuPanel sudokuPanel = new PuzzleSudokuPanel(); 
  PuzzleCalkuroPanel calkuroPanel = new PuzzleCalkuroPanel();

  screens = new JPanel(new CardLayout()); 
  screens.add(startPanel, "start");
  screens.add(choosePanel, "choosePuzzle");
  screens.add(sudokuPanel, "sudoku");
  screens.add(calkuroPanel, "calkuro");
  screens.setPreferredSize (new Dimension(250, 80));

  puzzle.setJMenuBar(menuBar);
  puzzle.getContentPane().add(screens);
  puzzle.pack();
  puzzle.setVisible(true);
  puzzle.setResizable(false);
  puzzle.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
}

static public void getUsername(String str){
  username = str;
}

static public void openWindow(String newFrame){
  CardLayout cl = (CardLayout)(screens.getLayout());
  cl.show(screens, newFrame);
}
}

Edit

brainblast tried to pack the frame after resetting the preferred size when openWindow is called, and wolah, new frame size :D

static public void openWindow(String newFrame, int a, int b){
  CardLayout cl = (CardLayout)(screens.getLayout());
  cl.show(screens, newFrame);
  screens.setPreferredSize (new Dimension(a, b));
  puzzle.pack();
}
like image 699
David Parsonson Avatar asked Oct 06 '22 06:10

David Parsonson


1 Answers

can i set the size of individual panels in a cardlayout

Certainly. But the layout will ignore them and make every card the same size. The best you can hope for is to add the smaller panels to another panel (with a layout) that allows the content to shrink.


This answer shows this technique using a single label. Swap the label for the 'small panels' and using the layouts on the right, it will be centered.

like image 89
Andrew Thompson Avatar answered Oct 16 '22 17:10

Andrew Thompson