Search code examples
javaswingjlabelnull-layout-manager

Changing a JLabel's position


After a lot of research I only could get that board image with using label. Now I cannot change it's position. I tried a lot of functions. What is the exact function do I need

public class Board extends JFrame {
    private ImageIcon image;
    private JLabel label;

    public Board() {
        image = new ImageIcon(getClass().getResource("board.png"));
        label = new JLabel(image);
        label.setLocation(200, 0);  //This is the one that I expected to do the thing
        add(label);
    }

    public static void main(String [] args) {
        Board b = new Board();
        b.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        b.setVisible(true);
        b.setSize(1280, 1000);
    }
}

Solution

  • First of all: you shouldn't move components manually. This should be left to the layoutmanager. But you can. The basic problem you're facing is - or atleast i think so - : you're board still has an layoutmanager set, which will continue to layout the board and due to this aswell move (and handle the size of) you're component. Just call setLayout(null); before positioning the label and specify the size and it should work.