AbsoluteLayoutPanel.java
package ac.essex.ooechs.imaging.commons.util.panels;
import javax.swing.*;
import java.awt.*;
import java.util.Vector;
/**
* Useful class for you to place things WHERE you want EASILY
* as opposed to using the awful Java layout managers.
*
* @author Olly Oechsle, University of Essex, Date: 12-Dec-2007
* @version 1.0
*/
public class AbsoluteLayoutPanel extends JPanel {
public static final int TOP = 1;
public static final int CENTER = 2;
public static final int BOTTOM = 3;
public static final int STRETCH = 4;
public int valign = TOP;
protected int hgap = 5;
protected int vgap = 5;
protected int x;
protected int y;
protected Insets insets;
private int rowHeight = 0;
private Vector<Component> line;
public static void main(String[] args) {
JFrame f = new JFrame();
AbsoluteLayoutPanel ab = new AbsoluteLayoutPanel();
ab.valign = STRETCH;
JTextField txt = new JTextField();
JButton b = new JButton("...");
ab.addRight("Testing:", 100);
ab.add(txt, 200);
ab.add(b);
ab.newRow();
JTextField txt2 = new JTextField();
JButton b2 = new JButton("...");
ab.addRight("Training:", 100);
ab.add(txt2, 200);
ab.add(b2);
f.add(ab);
f.setSize(640, 480);
f.setVisible(true);
}
public AbsoluteLayoutPanel() {
this(0, 0);
}
public AbsoluteLayoutPanel(int top, int left) {
setLayout(null);
insets = getInsets();
this.x = top + insets.left + hgap;
this.y = left + insets.top + vgap;
rowHeight = 0;
line = new Vector<Component>();
}
public Component add(String text) {
return add(new JLabel(text));
}
public Component add(String text, int width) {
return add(new JLabel(text), width);
}
public Component addRight(String text, int width) {
return add(new JLabel(text, JLabel.RIGHT), width);
}
public Component add(Component comp) {
Dimension size = comp.getPreferredSize();
return add(comp, size.width);
}
public Component add(Component comp, int width) {
Dimension size = comp.getPreferredSize();
size.width = width;
comp.setPreferredSize(size);
comp.setBounds(x, y, width, size.height);
x += width + hgap;
if (size.height > rowHeight) {
rowHeight = size.height;
// update everything on the line
for (int i = 0; i < line.size(); i++) {
Component component = line.elementAt(i);
Rectangle bounds = component.getBounds();
Dimension componentSize = component.getPreferredSize();
if (valign == STRETCH) {
componentSize.height = rowHeight;
component.setSize(componentSize);
}
if (valign == BOTTOM) {
int componentHeight = componentSize.height;
bounds.y = y + (rowHeight - componentHeight);
component.setBounds(bounds);
}
if (valign == CENTER) {
int componentHeight = componentSize.height;
bounds.y = y + ((rowHeight - componentHeight) / 2);
component.setBounds(bounds);
}
}
}
line.add(comp);
return super.add(comp); //To change body of overridden methods use File | Settings | File Templates.
}
public void newRow() {
newRow(rowHeight);
}
public void newRow(int height) {
x = insets.left + hgap;
y += height + vgap;
rowHeight = 0;
line = new Vector<Component>();
}
}