Absolute Layout in Swing

Guest Posts Steven





With Swing we have different layouts that we can use in our frame to set the different components, (JButtons, JTextFields,…), in a certain position. You can look at those layouts here.

In may case I usually use the Absolute Layout so I can control where my components are going to be positioned, using the function setBounds(), this function take 4 parameters: setBounds(int x, int y, int width, int height).

In this case I’m going to add a JButton and JTextField.

Here’s the example:

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JTextField;

public class exampleJFrame extends JFrame {

   private JPanel _panel;
   private JTextField textField;

   /**
   * Create the frame.
   */
   public exampleJFrame() {
      setVisible(true); //we make the window visible
      setResizable(false); // if write false, you won’t be able to resize the window
      setTitle(“Example”); //you set the title for the window
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setLocationRelativeTo(null); // you make the window appear at the center of the screen
      setSize(250,159); // you set the size of the window
      _panel = new JPanel();
      add(_panel);
      _panel.setLayout(null); // you set the Layout to null = Absolute Layout

      JButton btnClickMe = new JButton(“Click Me!”);
      btnClickMe.setBounds(86, 84, 89, 23); // you set the size and position of the button in the JPanel
      _panel.add(btnClickMe); // add the button to the JPanel

      textField = new JTextField();
      textField.setBounds(86, 11, 86, 20);
      _panel.add(textField);
   }

   public static void main(String[] args) {
      exampleJFrame example=new exampleJFrame();
   }
}



The result would be:

Image

That’s an example in how to control Layouts in Swing, and how to control the position and size of the different components in your JFrame.