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.
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);
}
}
One other component that admits this kind of layout is JList, which includes a VERTICAL_WRAP
that "Indicates a newspaper style layout with cells flowing vertically then horizontally." Depending on your needs, a suitable ListCellRenderer
, mentioned here, may be suffice.