I was just asked if there’s a way to layout Visual Library Widgets in a Grid. There’s no layout like that in the API, but if you need that, here’s a very basic solution to get started. The Layout is not very smart and all cells are of the same size ( maxWidth & maxHeight ), but it’s a start and it gives an idea how Layouts work:
[sourcecode language='java']
package de.eppleton.tablewidget;
import org.netbeans.api.visual.layout.Layout;
import org.netbeans.api.visual.widget.Widget;
import java.awt.*;
import java.util.*;
class TableLayout implements Layout {
private int columns;
public TableLayout(int columns) {
this.columns = columns;
}
public void layout(Widget widget) {
Collection children = widget.getChildren();
int posX = 0;
int posY = 0;
int col = 0;
int maxWidth = 0;
int maxHeight = 0;
for (Widget child : children) {
Rectangle preferredBounds = child.getPreferredBounds();
int width = preferredBounds.width;
int height = preferredBounds.height;
if (height > maxHeight) {
maxHeight = height;
}
if (width > maxWidth) {
maxWidth = width;
}
}
for (Widget child : children) {
Rectangle preferredBounds = child.getPreferredBounds();
int x = preferredBounds.x;
int y = preferredBounds.y;
int width = preferredBounds.width;
int height = preferredBounds.height;
int lx = posX - x;
int ly = posY - y;
if (child.isVisible()) {
child.resolveBounds(new Point(lx, ly), new Rectangle(x, y, width, height));
posX += maxWidth;
} else {
child.resolveBounds(new Point(lx, ly), new Rectangle(x, y, 0, 0));
}
col++;
if (col == columns) {
col = 0;
posX = 0;
posY += maxHeight;
}
}
}
public boolean requiresJustification(Widget widget) {
return false;
}
public void justify(Widget widget) {
}
}
[/sourcecode]
You can use it like that:
[sourcecode language='java']
package de.eppleton.tablewidget;
import org.netbeans.api.visual.widget.Scene;
import org.netbeans.api.visual.widget.Widget;
public class TableWidget extends Widget {
public TableWidget(Scene scene, int columns) {
super(scene);
setLayout(new TableLayout(columns));
}
}
[/sourcecode]
To test it create a Scene and add this:
[sourcecode language='java']
TableWidget table = new TableWidget(scene, 3);
table.addChild(new LabelWidget(scene, “1″));
table.addChild(new LabelWidget(scene, “2.”));
table.addChild(new LabelWidget(scene, “3″));
table.addChild(new LabelWidget(scene, “4.”));
table.addChild(new LabelWidget(scene, “5″));
table.addChild(new LabelWidget(scene, “6″));
table.addChild(new LabelWidget(scene, “7″));
table.addChild(new LabelWidget(scene, “8″));
table.addChild(new LabelWidget(scene, “9…”));
scene.addChild(table);
[/sourcecode]
This should give you a simple grid to start with.