Question:
Do you know of any LayoutManager that would allow me to lay out components exactly where I want them, or any other way of doing so?
Answer:
There is no standard AWT or Swing LayoutManager implementation that will perform absolute positioning of components. Instead, java.awt.Component, and therefore every subclass of Component, contains a setLocation method that allows a component to be positioned using coordinates that are interpreted relative to the component’s parent container. To position components absolutely without any interference from a layout manager, you have to set the layout manager of the container to null. You also have to set the sizes of your components explicitly, not relying on a layout manager to size your components for you automatically. The following code listing demonstrates how to do this. It places a button inside a frame at a randomlocation. Every time you press the button, it moves itself to a new random location within the frame.
import java.awt.*;import java.awt.event.*;public final class AbsoluteLayout { public static int random(int min, int range) { double dRange = range; double result; result = Math.rint(Math.random()*dRange); return (int)(min + (int)result); } public static void main(String[] args) { Button button; Frame frame; WindowListener exitListener; exitListener = new WindowAdapter() { public void windowClosing(WindowEvent e) { Window window = e.getWindow(); window.setVisible(false); window.dispose(); System.exit(0); } }; button = new Button("Press me"); // Explicitly size the button, otherwise it will be a mere point. button.setSize(100, 25); // Add an ActionListener that will randomly move the button button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Component source, parent; Dimension sourceSize, parentSize; source = (Component)e.getSource(); sourceSize = source.getSize(); parent = source.getParent(); parentSize = parent.getSize(); source.setLocation(random(0, parentSize.width - sourceSize.width), random(0, parentSize.height - sourceSize.height)); } }); frame = new Frame(); // Don't forget to set the layout manager to null! Otherwise it will // interfere with your positioning and sizing. frame.setLayout(null); frame.add(button); frame.addWindowListener(exitListener); frame.setSize(400, 400); // Dispatch an initial event to randomly place the button. button.dispatchEvent( new ActionEvent(button, ActionEvent.ACTION_PERFORMED, null)); frame.setVisible(true); }}