.setBounds not working for JLabel and JButton

对着背影说爱祢 提交于 2019-11-28 02:29:40

Don't use setBounds() to set the size and location of a component.

Let the layout manager do its job. That is if fact what is happening. A JPanel uses a FlowLayout, so the components are being positioned based on the rules of the FlowLayout. You can change the FlowLayout to align components to the left if you want. Or you can use a different layout manager.

Read the Swing tutorial on Layout Managers to find other layout managers you can use.

public yo() {
    frame.add(panel);
    frame.setTitle("Hello");
    frame.setSize(500,500);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
    frame.setLocationRelativeTo(null);
    panel.setLayout(null);
    panel.add(heloo);
    panel.add(button);
    button.setBounds(200,100,200,100);
    heloo.setBounds(100,100,100,100);
    button.addMouseListener(this);
}

By setting the layout of the JPanel to null, it will be in the "Absolute Layout", and then you'll be able to set the position of the JLabel and JButton with setBounds().

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!