JToggleButtons stretching to fill entire JFrame regardless of setSize

1 day ago 1
ARTICLE AD BOX

I am trying to create a simple Java Swing application with a custom drawing canvas and a set of JToggleButton controls. However, the buttons are currently stretching to cover the entire window, obscuring my canvas and each other.

I have tried using btn.setSize(10, 10), but the buttons still expand to fill the whole frame. I suspect this has to do with the default Layout Manager, but I'm not sure how to organize them so they sit neatly (for example, in a row) without covering the MyCanvas component.

Code:

import java.awt.*; import javax.swing.*; class Main { public static void main(String[] args) { JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(500, 525); // Custom canvas MyCanvas canvas = new MyCanvas(); frame.add(canvas); // Group for buttons ButtonGroup buttonGroup = new ButtonGroup(); // Creating buttons createButton("move", frame, buttonGroup); createButton("grass", frame, buttonGroup); createButton("water", frame, buttonGroup); createButton("hole", frame, buttonGroup); createButton("mountain", frame, buttonGroup); frame.setVisible(true); } private static JToggleButton createButton(String btnname, JFrame frame, ButtonGroup buttonGroup) { JToggleButton btn = new JToggleButton(btnname); btn.setSize(10, 10); // This doesn't seem to affect the size buttonGroup.add(btn); frame.add(btn); // Adding directly to frame seems to cause the overlap/fill issue return btn; } } // Placeholder for the canvas class class MyCanvas extends JComponent { @Override public void paintComponent(Graphics g) { g.setColor(Color.WHITE); g.fillRect(0, 0, getWidth(), getHeight()); } } I've tried adjusting them manually using setSize but it doesn't seem to work.
Read Entire Article