Absolute Positioning

It’s possible to set the layout manager to null: no layout control. You might do this to position an object on the display at some absolute coordinates. This is almost never the right approach. Components might have different minimum sizes on different platforms, and your interface would not be very portable.

The following example doesn’t use a layout manager and works with absolute coordinates instead:

//file: MoveButton.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class MoveButton extends JPanel {
  JButton button = new JButton("I Move");  

  public MoveButton( ) {
    setLayout(null);  
    add(button);
    button.setSize(button.getPreferredSize( ));  
    button.setLocation(20, 20);
    addMouseListener(new MouseAdapter( ) {
      public void mousePressed(MouseEvent e) {
      button.setLocation(e.getX(), e.getY( ));
      }
    });
  }

  public static void main(String[] args) {
    JFrame f = new JFrame("MoveButton");
    f.addWindowListener(new WindowAdapter( ) {
      public void windowClosing(WindowEvent e) { System.exit(0); }
    });
    f.setSize(250, 200);
    f.setLocation(200, 200);
    f.setContentPane(new MoveButton( ));
    f.setVisible(true);
  }
}

Click in the window area, outside of the button, to move the button to a new location. Try resizing the window and note that the button stays at a fixed position relative to the window’s upper left corner.

Get Learning Java now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.