The layout manager really does 3 things:
Set the location of the component. Since you need the ability to drag a component around, you do not want your layout manager to do this.
Set the size of the component. Since you need to resize the component, you will not want to do this. However, you might want to give the component a default size based on the preferred size of the components. Thus, you do not need to specify the size when creating the component.
Determine the preferred size of the parent panel based on the components added to it. This will allow you to use the scrollbars correctly, as scrollbars can be added / removed as needed. Therefore, you need to determine how to work with drag and drop. That is, you can drag a component beyond the current border of the panel. If so, the preferred panel size should automatically increase.
Is there an already implemented LayoutManager that allows absolute component positioning
I played with a layout manager that is close to your needs. It was designed for use with the ComponentMover class from Moving Windows
provided by trashgod.
Here is my test code for this class:
import java.awt.*; import javax.swing.*; import javax.swing.border.*; public class DragLayout implements LayoutManager, java.io.Serializable { public DragLayout() { } @Override public void addLayoutComponent(String name, Component comp) {} @Override public void removeLayoutComponent(Component component) { } @Override public Dimension minimumLayoutSize(Container parent) { synchronized (parent.getTreeLock()) { return preferredLayoutSize(parent); } } @Override public Dimension preferredLayoutSize(Container parent) { synchronized (parent.getTreeLock()) { return getLayoutSize(parent); } } private Dimension getLayoutSize(Container parent) { Insets parentInsets = parent.getInsets(); int x = parentInsets.left; int y = parentInsets.top; int width = 0; int height = 0;
For this layout, size is always considered preferred. You will need to change this. Size may be preferable if the size is (0, 0). When determining the preferred size of the parent container, you will also need to use the size of the component (not its preferred size).
The ComponentMover class can be customized so that you can drag comopnents outside the parent container or maintain the component inside the borders. If you allow components to be moved outside, the preferred size is automatically adjusted to take into account the new location of the component.
If you drag a component outside the top or left borders, then all components are shifted (right or down), make sure that the component does not have a negative location.
source share