Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to place a JButton at a desired location in a JFrame using Java

Tags:

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

This is 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)?

like image 506
Haxed Avatar asked Jul 07 '10 14:07

Haxed


People also ask

How do you change the position of a button in Java?

In the absence of a layout manager, the position and size of the components must be set manually. setBounds() method is used to set the position and size. To manually specify the position and size of the components, the layout manager of the frame can be null.

How do you center something in a JFrame?

By default, a JFrame can be displayed at the top-left position of a screen. We can display the center position of JFrame using the setLocationRelativeTo() method of Window class.

What is JButton in Java Swing?

The class JButton is an implementation of a push button. This component has a label and generates an event when pressed. It can also have an Image.


1 Answers

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.

like image 140
Eugene Ryzhikov Avatar answered Sep 25 '22 18:09

Eugene Ryzhikov