I'm looking for a LayoutManager
that will allow me to show a set of components in a container (e.g. a JPanel), in columns, roughly as follows.
- The container's width is an input constraint.
- The container's preferred height is a function of the width, and is either:
- the minimum height needed to get the components to fit within the width, when laid out in more than one column.
- the minimum height needed to get the components to fit in a single column.
- The components will be placed in a newspaper-column order, from top to bottom and then from left to right.
Here's an example (low-tech text display) showing 13 components. If they can fit in 3 columns, they would look like this:
Foo1 Foo6 Foo11
Foo2 Foo7 Foo12
Foo3 Foo8 Foo13
Foo4 Foo9
Foo5 Foo10
If that's too wide, they'd look like this:
Foo1 Foo8
Foo2 Foo9
Foo3 Foo10
Foo4 Foo11
Foo5 Foo12
Foo6 Foo13
Foo7
And if that's too wide, they'd look like this:
Foo1
Foo2
Foo3
Foo4
Foo5
Foo6
Foo7
Foo8
Foo9
Foo10
Foo11
Foo12
Foo13
Is there a pre-existing LayoutManager that I can use or subclass to do something like this?
edit: this is very close to this other question about vertical layout, but that layout has the component height being the constraint, and mine has the component width being a constraint.
you might want to look into GribBagLayout http://download.oracle.com/javase/tutorial/uiswing/layout/gridbag.html
With gridbag layout knowing the size you can set how many components you would have in a particular row.
but if i am not mistaken shouldnt gridlayout do exactly what you want.
lets go with the simple labels. if the size*2 of the label is longer than the width, then it will show only 1 label per row. and so on.
here is an example which should clear it up
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GridLayoutDemo implements ActionListener{
JTextField j1;
JTextField j2;
JFrame f;
public void show(){
j1=new JTextField("x dimention");
j2=new JTextField("y dimention");
f=new JFrame();
JPanel p=new JPanel();
JLabel l2=new JLabel("abcdefghijklmnoqrstuvw");
JLabel l1=new JLabel("abcdefghijklmnoqrstuvw");
JLabel l3=new JLabel("abcdefghijklmnoqrstuvw");
JLabel l4=new JLabel("abcdefghijklmnoqrstuvw");
JButton b=new JButton("new size");
b.addActionListener(this);
p.add(l1);
p.add(l2);
p.add(l3);
p.add(l4);
p.add(j1);
p.add(j2);
p.add(b);
f.setSize(400, 200);
f.add(p);
//f.pack();
f.setVisible(true);
}
public static void main(String[] args){
GridLayoutDemo g=new GridLayoutDemo();
g.show();
}
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
int x=Integer.parseInt(j1.getText());
int y=Integer.parseInt(j2.getText());
f.setSize(x,y);
f.setVisible(true);
}
}
来源:https://stackoverflow.com/questions/6311772/swing-column-flow-layout-manager