views:

64

answers:

2

Hey, I want to put a Jbutton on a particular coordinate in a JFrame. I put setBounds for the JPanel (which I placed on the JFrame) and also setBounds for the JButton. However, they dont seem to function as expected.

My Output:

alt text


My Code:

import java.awt.Color;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Control extends JFrame {

//JPanel
JPanel pnlButton = new JPanel();
//Buttons
JButton btnAddFlight = new JButton("Add Flight");

public Control() {

    //FlightInfo setbounds
    btnAddFlight.setBounds(60, 400, 220, 30);

    //JPanel bounds
    pnlButton.setBounds(800, 800, 200, 100);


    //Adding to JFrame
    pnlButton.add(btnAddFlight);
    add(pnlButton);

    // JFrame properties
    setSize(400, 400);
    setBackground(Color.BLACK);
    setTitle("Air Traffic Control");
    setLocationRelativeTo(null);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setVisible(true);



}

public static void main(String[] args) {

    new Control();

}
}

How can place the JButton at coordinate (0,0) ?

Many Thanks

+1  A: 

Use child.setLocation(0, 0) on the button, and parent.setLayout(null). Instead of using setBounds(...) on the JFrame to size it, consider using just setSize(...) and letting the OS position the frame.

//JPanel
JPanel pnlButton = new JPanel();
//Buttons
JButton btnAddFlight = new JButton("Add Flight");

public Control() {

    //JFrame layout
    this.setLayout(null);

    //JPanel layout
    pnlButton.setLayout(null);

    //Adding to JFrame
    pnlButton.add(btnAddFlight);
    add(pnlButton);

    // postioning
    pnlButton.setLocation(0,0);
Chadwick
The Java tutorial recommends `setBounds`. `setLocation` just delegates to `setBounds` anyway.
Mark Peters
@Mark_Peters True, though I was (perhaps wrongly) assuming that in asking to set the position, like most apps, the JButton was to be sized automatically. `setLocation` does invoke `setBounds`, but it uses the components current width and height, letting it size naturally based on contents. Typical, but you're right, not always what is wanted.
Chadwick
i used setBounds for the button and made the panel layout null. It works for me. Thks
Haxed
+3  A: 

Following line should be called before you add your component

pnlButton.setLayout(null);

Above will set your content panel to use absolute layout. This means you'd always have to set your component's bounds explicitly by using setBounds method.

In general I wouldn't recommend using absolute layout.

eugener
See: http://java.sun.com/docs/books/tutorial/uiswing/layout/none.html
Mark Peters
i used setBounds for the button and made the panel layout null. It works for me. Thks
Haxed