Skip to Content
Learning Java, 4th Edition
book

Learning Java, 4th Edition

by Patrick Niemeyer, Daniel Leuck
June 2013
Beginner
1007 pages
33h 32m
English
O'Reilly Media, Inc.
Content preview from Learning Java, 4th Edition

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 absolute coordinates. This is usually not the right approach. Components might have different minimum sizes on different platforms, so 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 frame = new JFrame("MoveButton");
        frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        frame.setSize(250, 200);
        frame.setLocation(200, 200);
        frame.setContentPane(new MoveButton());
        frame.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.

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learning Java, 6th Edition

Learning Java, 6th Edition

Marc Loy, Patrick Niemeyer, Daniel Leuck
Learning Java, 5th Edition

Learning Java, 5th Edition

Marc Loy, Patrick Niemeyer, Daniel Leuck
Head First Java, 3rd Edition

Head First Java, 3rd Edition

Kathy Sierra, Bert Bates, Trisha Gee
Java in a Nutshell, 7th Edition

Java in a Nutshell, 7th Edition

Benjamin J. Evans, David Flanagan

Publisher Resources

ISBN: 9781449372477Errata PageSupplemental Content