简体   繁体   中英

JLabel ignoring setBounds Method

public class Window extends JFrame {

public Window() {
    super("Whatever Window idk");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setSize(300, 300);
    setLocationRelativeTo(null);
    setVisible(true);

    JLabel label1 = new JLabel();
    label1.setText("label1");
    label1.setBounds(40, 20, 100, 30);

    JLabel label2 = new JLabel();
    label2.setText("label2");
    label2.setBounds(40, 20, 100, 30);

    JLabel label3 = new JLabel();
    label3.setText("label3");
    label3.setBounds(40, 20, 100, 30);

    add(label1);
    add(label2);
    add(label3);
}

public static void main(final String[] args) {
    new Window();
}

I constructed label1 with given bounds. These bounds should put my label in the upper left corner to center of the window.

That was not the case as the label was placed in the center left bound of the window.

Then, after changing the bounds did not work, I created label2 with the same bounds, to check if the lines would "merge" or something. Turns out, adding label 2 pushes label 1 into the correct location (as defined in setBounds() ) and places label 2 in its stead on the leftmost center position. Now, adding label 3 with the exact same bounds does the same thing with label 2. So label 1 and 2 merge in the defined bounds while label 3 is placed left-center.

My question: Why?

Done in IntelliJ IDEA.

You have 2 options

1)set the frames content pane to an panel having null layout

 setContentPane(new JPanel(null));

2)set the existing content pane layout to null

 getContentPane().setLayout(null);

add either of these 2 lines after u have called the super() method

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM