Jones
Jones

Reputation: 21

Why can't I position the JButton using setLocation in this code?

I am very new and still have a lot to learn. Thank you so much for anyone who takes the time to help me with this. I have tried a variety of different methods to position my button at specific coordinates with the frame, but for some reason, none of the usual statements that work for placing JButtons is working. Any suggestions?

Here is my current working code

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

class GUI extends JFrame
{

JButton b1; // Declares Swing button variable and gives identifier (b1)
JButton b2;  // Declares Swing label variable and gives identifier (l1)

public GUI()
{
setTitle("Virus Explortation");
setSize(400,400);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);

setLayout(new BorderLayout());
setContentPane(new JLabel(new ImageIcon("C:\\Pictures\\matrix.gif")));
setLayout(new FlowLayout());
b1=new JButton("I am a button");
add(b1);

b2=new JButton("I am also a button");
add(b2);

setSize(399,399);
setSize(400,400);


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

Upvotes: 2

Views: 1586

Answers (1)

user3437460
user3437460

Reputation: 17454

Why can't I position the JButton using setLocation in this code?

It is because all the containers in Java swing has a default layout. You are adding the button directly into the JFrame where I see you using a BorderLayout for the frame. (BorderLayout is also the default layout for JFrame).

When a layout is used, the layout manager will decide on the position (and sometimes the dimension) for your added components. Which means your attempt of manually setting the position may become futile.

If you want to set the components' position to exactly where you want, you will have to set the layout of the container (such as JFrame or JPanel) to null:

JPanel pnlMain = new JPanel();
pnlMain.setLayout(null);

After you set it to null, you will have to set the location for every components you add to the container. If not, it won't show up. You may use the setBounds method to set the size and location:

JButton btn = new JButton();
btn.setBounds(x, y, width, height);

However, setting layout to null is not recommended for many reasons. One of the most prominent reason being that you loses control and predictability on how your UI will present on different Systems and different usage by the users.


It is also advisable not to extends from JFrame but rather extends from a container like JPanel. Then add the container to the frame. It is quite rare that you need to make a customized JFrame.

Upvotes: 2

Related Questions