Hi people,

How can I put a JRadioButton wherever I want in a JPanel? I tried setLocation() but it did not change anything. It is still on the north-center part of the panel. I think I'm missing something, but I can't figure it out. Thank you in advance.

Dani AI

Generated

Good call by and well done for finding the fix — a layout manager will override manual positioning, so disabling it and giving the component explicit bounds is the usual quick solution. A few practical notes that clarify why setLocation appeared to do nothing and what to watch for when using absolute positioning.

Layout managers (BorderLayout, FlowLayout, etc.) ignore component locations and sizes you set. If a component ends up in the "north/center" area that points to a BorderLayout on the container. setBounds(x,y,w,h) sets both position and size; setLocation alone won't help if the size is controlled elsewhere or is zero. Also make GUI changes on the Event Dispatch Thread to avoid flaky behavior. If pack() is used, remember it respects preferred sizes — with a null layout either set a preferred size for the container or set the frame size explicitly.

Example pattern (run on the EDT) for absolute placement:

SwingUtilities.invokeLater(() -> {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel panel = new JPanel(null); // no layout manager
    JRadioButton rb = new JRadioButton("Option");
    rb.setBounds(20, 30, 120, 22); // x, y, width, height
    panel.add(rb);
    panel.setPreferredSize(new Dimension(300, 200));
    frame.setContentPane(panel);
    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
});

Prefer layout managers for production UIs (nested panels + GridBagLayout, BoxLayout, GroupLayout, or a third‑party like MigLayout) because absolute positioning breaks on resize, different font/DPI settings, and localization. Quick troubleshooting checklist: confirm the right container has setLayout(null), ensure nonzero component size, call revalidate()/repaint() after changes, avoid modifying Swing components off the EDT, and beware pack() semantics.

Recommended Answers

All 5 Replies

Did you remove the layout manager so that you have exclusive control vs competing with the layout manager over who gets to set the location of a component?

yes, there is no layout manager for that panel.

Can you post a small program that compiles, executes and shows the problem?

Thank you for your concern, but I fixed it. I set the layout null and use setBounds() method for the radio button.

Glad you found it. That was what I was saying about the layout manager: remove the layout manager.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.