0

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);
}
Abra
  • 19,142
  • 7
  • 29
  • 41
  • 1
    `setLocation`/`setBounds` is ill advised. See [Laying Out Components Within a Container](https://docs.oracle.com/javase/tutorial/uiswing/layout/index.html) for a better starting point – MadProgrammer Oct 31 '22 at 04:14

1 Answers1

0

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.

Abra
  • 19,142
  • 7
  • 29
  • 41
  • thanks, @Abra, I'm new at using Swing so I didn't know that it was possible to set a background on a JPanel. I've tried to use a Layout for organizing the components but I saw that, for the project that I'm working on, it wouldn't have been useful, due to the limitations when it comes to customizing the GUI. Even so, I'll try to refactor the code following your feedback and also use the Layouts, You surely can make really complex GUIs with them but as an amateur, it becomes really difficult. Thanks for your time! – Hazzard_09 Oct 31 '22 at 06:55