andor kesselman
andor kesselman

Reputation: 1179

JPanel Format Problems

I have a 2 JPanels, 1 a button Panel and one a Graphic Panel. I would like the button panel to situated right below the graphic panel but the button panel cuts off the Graphics Panel in the middle. I've been trying the box layout which seems from discussions seems like the best format for what I am trying to do. Can anyone please give me some advice on my formatting problem.

    JFrame canvas = new JFrame("Baseball Strike K");


    JFrame canvas = new JFrame ("GraphicBoard");
      canvas.setVisible(true);
      canvas.setSize(1000,1000);
      canvas.setDefaultCloseOperation(EXIT_ON_CLOSE);
//create two panels
//add them to contentPane

//set Layout
      JPanel buttonPanel = createButtons();
      JPanel mainPanel = new Graphic(); //extends JPanel and writes the paint method
      mainPanel.setSize(1000, 1000);

      Container content = canvas.getContentPane();
      content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS));
      content.add(mainPanel);
      content.add(buttonPanel);

Upvotes: 0

Views: 649

Answers (1)

camickr
camickr

Reputation: 324207

mainPanel.setSize(1000, 1000);

The job of the layout manager is to determine the size of the component, so you would never invoke the setSize() method of a components.

Instead you give hints to the layout manager on what the size should be. You would do this by overriding the getPreferredSize() method to return an appropriate value. Also, I would pick a more reasonable size (1000, 1000) is a little big to display on most screens. If you really want your painting area this large then I would add the paint panel to a JScrollPane and then add the scrollpane to the frame.

Try getting your code to work using a BoxLayout. Then I would suggest a better layout manager would be to use a BorderLayout. Then you add the paint panel to the CENTER and the buttons to the SOUTH. Now as you resize the frame the paint panel will be adjusted in size.

canvas.setVisible(true);

Also, the placement of that line of code is wrong. You should add all your components to the frame first, before making the frame visible.

Upvotes: 1

Related Questions