June 2013
Beginner
1007 pages
33h 32m
English
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.javaimportjava.awt.*;importjava.awt.event.*;importjavax.swing.*;publicclassMoveButtonextendsJPanel{JButtonbutton=newJButton("I Move");publicMoveButton(){setLayout(null);add(button);button.setSize(button.getPreferredSize());button.setLocation(20,20);addMouseListener(newMouseAdapter(){publicvoidmousePressed(MouseEvente){button.setLocation(e.getX(),e.getY());}});}publicstaticvoidmain(String[]args){JFrameframe=newJFrame("MoveButton");frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setSize(250,200);frame.setLocation(200,200);frame.setContentPane(newMoveButton());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.