Search code examples
javaswingpositionlayout-managerjcomponent

Java - set the exact position of a JComponent


I need help with setting the x and y position of a JLabel on a JPanel, not North,South,West,East.

Thank you for your time.


Solution

  • To have a JPanel respect exact locations, you should set its layout to null. Then, you can use setLocation on any JComponent to set its location within that JPanel.

    JPanel panel = new JPanel();
    panel.setLayout(null);
    JLabel label = new JLabel("text");
    label.setLocation(50, 20);
    panel.add(label);
    

    However, note that there are several downsides of absolute position (mentioned in comments below), and that you should utilize a LayoutManager to position your components.