Pedro Pereira
Pedro Pereira

Reputation: 55

Auto resizing a JFrame with pack() without collapsing its jPanels

i am trying to design a JFrame with 2 different JPanels in it, one on the left with AbsoluteLayout and one on the right with a GridLayout with variable dimensions.

After adding some components to the JPanels, i add them to the JFrame contentPane and use the method JFrame.pack() hoping to get a JFrame with the minimum size possible that can show all of its components, but what i am getting is the minimum size to show only the JPanel on the right with the GridLayout, the JPanel on the left gets overlapped by the one on the right.

Is there any good way to use the JFrame.pack() method and it still shows both JPanel completly?

Here is the code:

public class GameGUI extends JFrame{

   private int labSize;
   private JFrame mainFrame;
   private JPanel labPanel;
   private JPanel choicesPanel;
   private JButton exitButton;
   private JButton replayButton;

   public GameGUI(int n) {

        labSize=n;    
        mainFrame = new JFrame("Maze Game");
        mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        mainFrame.getContentPane().setLayout(new GridLayout(1, 0));
        mainFrame.setVisible(false);    
        labPanel=new JPanel(new GridLayout(labSize,labSize));    
        choicesPanel=new JPanel(new GridLayout(0, 1));
        choicesPanel.setLayout(null);           
        replayButton=new JButton("Replay");
        replayButton.setBounds(10, 11, 80, 30);         
        exitButton=new JButton("Exit");
        exitButton.setBounds(10, 51, 80, 30);    
        choicesPanel.add(replayButton);
        choicesPanel.add(exitButton);           
        mainFrame.getContentPane().add(choicesPanel);
        mainFrame.getContentPane().add(labPanel);
    }

    public void refreshLabShowing(char[][] lab){

        labPanel.removeAll();    
        for(int i=0;i<labSize;i++){
            for(int u=0;u<labSize;u++){
                labPanel.add(new JLabel(String.valueOf(lab[i][u])));
            }
        }           
        mainFrame.pack();
        mainFrame.setVisible(true);
    }
}

Upvotes: 1

Views: 403

Answers (1)

Antoniossss
Antoniossss

Reputation: 32527

pack() will only work if with layout managers, as pack() itself queries layout manager for required dimension so here, you cannot use absolute layout and pack().

Upvotes: 2

Related Questions