Could anyone point out where I am going wrong with this java swing gui code. I am trying to add two buttons to a JPanel and then add it into a frame after setting the size but it seems to not be responding to the setSize values passed to it
public Test() {
GridLayout layout = new GridLayout(1, 2);
//this.setLayout(layout);
this.setSize(700, 700);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
buttonPanel = new JPanel();
buttonPanel.setSize(new Dimension(30, 100));
JButton rectButton = new JButton("Rectangle");
JButton ovalButton = new JButton("Oval");
buttonPanel.add(rectButton);
buttonPanel.add(ovalButton);
this.add(buttonPanel);
this.add(new PaintSurface());
this.setVisible(true);
}
This may not answer your immediate question…but…
You set the layout as a
GridLayout, but you are usingBorderLayoutconstraints to apply one of the components??Also, make sure that there are not calls to
Test#packelse where in your code, as this will override the values ofsetSizeUPDATED (from changes to question)
Remember, the default layout manager for
JFrameisBorderLayout, so even though you’re callingbuttonPanel.setSize, it’s likely that it’s begin overridden by the layout manager anyway.I would take a read through A Visual Guide to Layout Managers and Using Layout Managers to find a layout manager that best meets your requirements.
If you can’t find a single one, consider using compound components with different layout managers to bring the layout closer to what you want to achieve.