SAJC
asked on
implement grid in java.awt - cells span multiple columns
Hi,
I need to create a grid like component in java.awt (not using Swing) where cells span multiple rows.
Has anyone done this?
Thanks
I need to create a grid like component in java.awt (not using Swing) where cells span multiple rows.
Has anyone done this?
Thanks
not that i'm aware of , not much is done using straigt awt these days.
You can get far by using a GridBagLayout:
/*
* Copyright (c) 2007, Your Corporation. All Rights Reserved.
*/
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
/**
* @author Bart Cremers
* @since 6-dec-2007
*/
public class GridExample extends Panel {
private static final GridBagConstraints gbc = new GridBagConstraints();
static {
gbc.fill = GridBagConstraints.BOTH;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
}
public GridExample() {
super(new GridBagLayout());
add(new BorderedLabel("A"), 1, 1, 1, 1);
add(new BorderedLabel("B"), 1, 2, 1, 1);
add(new BorderedLabel("C"), 1, 3, 1, 1);
add(new BorderedLabel("D"), 1, 4, 1, 1);
add(new BorderedLabel("E"), 1, 5, 1, 1);
add(new BorderedLabel("F"), 2, 1, 1, 3);
add(new BorderedLabel("G"), 2, 4, 1, 1);
add(new BorderedLabel("H"), 2, 5, 3, 1);
add(new BorderedLabel("I"), 3, 1, 1, 1);
add(new BorderedLabel("J"), 3, 2, 2, 2);
add(new BorderedLabel("K"), 3, 4, 1, 1);
add(new BorderedLabel("L"), 4, 1, 1, 1);
add(new BorderedLabel("M"), 4, 4, 1, 1);
add(new BorderedLabel("N"), 4, 5, 1, 1);
}
private void add(Component comp, int row, int col, int rowspan, int colspan) {
gbc.gridx = col;
gbc.gridy = row;
gbc.gridwidth = colspan;
gbc.gridheight = rowspan;
add(comp, gbc);
}
public static void main(String[] args) {
final Frame frame = new Frame();
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
frame.dispose();
}
});
frame.add(new GridExample());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private static class BorderedLabel extends Label {
private BorderedLabel(String text) {
super(text, CENTER);
}
public void paint(Graphics g) {
super.paint(g);
g.setColor(getForeground());
g.drawRect(0, 0, getWidth() - 1, getHeight() - 1);
}
}
}
ASKER
Thanks for the above Bart, however, my fault, I should have stated I can't use GridBagLayout.
Sorry for late reply.
Sorry for late reply.
What's the reason for not being able to use gridbaglayout? It's available in AWT.
ASKER
The reason for not using any of the AWT layouts is that the number of rows and columns are arbitrary.
Will not know these till runtime.
thanks
Will not know these till runtime.
thanks
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
ok, thanks Bart