Code
class TabLayout implements LayoutManager, java.io.Serializable {
public void addLayoutComponent(String name, Component comp) {}
public void removeLayoutComponent(Component comp) {}
public Dimension preferredLayoutSize(Container parent) {
synchronized (parent.getTreeLock()) {
Insets insets = parent.getInsets();
int last = parent.getComponentCount()-1;
int w = 0, h = 0;
if(last >= 0) {
Component comp = parent.getComponent(last);
Dimension d = comp.getPreferredSize();
w = d.width;
h = d.height;
}
return new Dimension(insets.left + insets.right + w,
insets.top + insets.bottom + h);
}
}
public Dimension minimumLayoutSize(Container parent) {
synchronized (parent.getTreeLock()) {
return new Dimension(100, 24);
}
}
public void layoutContainer(Container parent) {
synchronized (parent.getTreeLock()) {
Insets insets = parent.getInsets();
int ncomponents = parent.getComponentCount();
int nrows = 1;
int ncols = ncomponents-1;
//boolean ltr = parent.getComponentOrientation().isLeftToRight();
if (ncomponents == 0) {
return;
}
int lastw = parent.getComponent(ncomponents-1).getPreferredSize().width;
int width = parent.getWidth() - (insets.left + insets.right) - lastw;
int h = parent.getHeight() - (insets.top + insets.bottom);
int w = (width > 100*(ncomponents-1))?100:width/ncols;
int gap = width - w*ncols;
int x = insets.left;
int y = insets.top;
for (int i=0;i < ncomponents;i++) {
int a = (gap > 0)?1:0;
gap--;
int cw = (i==ncols)?lastw:w+a;
parent.getComponent(i).setBounds(x, y, cw, h);
x += w + a;
}
}
}
public String toString() {
return getClass().getName();
}
}
References