Search code examples
javaswingjbuttonsetbounds

can't relocate a JButton object in a window


I've been trying to resize the button or to use the setLocation and setBounds methods. It doesn't matter whatever I put in the args the button just never changes. I need to learn to relocate whether a button, a label, a textfield, any component in the GUI.

Thanks in advance!

private void iniciarComponentes(){
    setTitle("PARA QUE SIRVE");
    setSize(1280,800);
    setLocationRelativeTo(null);
    setDefaultCloseOperation(HIDE_ON_CLOSE);
    getRootPane().setWindowDecorationStyle(JRootPane.NONE);
    setUndecorated(true);
    setVisible(true);
    
    setLayout(new BorderLayout());
    JLabel background = new JLabel(new ImageIcon("C:\\..."));
    add(background);
    background.setLayout(new FlowLayout());
    JButton btnOk = new JButton("OK");
    Dimension size = btnOk.getPreferredSize();
    btnOk.setBounds(0,0, 10, 10);
    btnOk.addActionListener(this);
    background.add(btnOk);
}

Solution

  • You need to use an appropriate layout manager, one that considers setLocation and setBounds – or not use a layout manager at all.

    I believe either SpringLayout or GroupLayout are appropriate.

    Alternatively, you could nest containers and use different layout managers. You would probably also need to manipulate the container sizes when nesting layouts.

    Also note that after you change the location of a component within a container (after the GUI is displayed) you will probably need to call method revalidate and possibly, after that, to call method repaint.

    Regarding the code in your question. It looks like the method, whose code you posted, is from a class that extends JFrame. It is not necessary that your GUI application class extends JFrame.

    Also from the code in your question:

    setLayout(new BorderLayout());
    

    This is the default so no need to explicitly set it.

    background.add(btnOk);
    

    Components such as JButton should be added to a container like JPanel and not to a JLabel. You can set a background image on a JPanel.