Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Swing setting JPanel Size

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);  
}
like image 994
cobie Avatar asked Nov 22 '25 07:11

cobie


1 Answers

This may not answer your immediate question...but...

GridLayout layout = new GridLayout(1, 2);
this.setLayout(layout);
// You're original code...
// Why are you using `BorderLayout.CENTER` on a `GridLayout`
this.add(new PaintSurface(), BorderLayout.CENTER);

You set the layout as a GridLayout, but you are using BorderLayout constraints to apply one of the components??

Also, make sure that there are not calls to Test#pack else where in your code, as this will override the values of setSize

UPDATED (from changes to question)

Remember, the default layout manager for JFrame is BorderLayout, so even though you're calling buttonPanel.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.

like image 172
MadProgrammer Avatar answered Nov 24 '25 21:11

MadProgrammer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!