If I use GridLayout
or BoxLayout
for bunch of JTextField
and JLabel
pairs it will equally split are of JPanel
among the text-fields.
it looks like this:
What I want looks like this ( with text-fields squeezed to the top ):
and I was able to achive that following this answer. The code is:
public void forceSize( int szx, int szy, JComponent comp ){
comp.setPreferredSize( new Dimension( szx, szy ) );
comp.setMaximumSize ( new Dimension( szx, szy ) );
comp.setMinimumSize ( new Dimension( szx, szy ) );
};
public void addLabeledBox( String label_str, JTextField valField, JPanel labelPane, JPanel valuePane ){
JLabel label = new JLabel( label_str );
label.setLabelFor( valField );
labelPane.add( label );
forceSize( 100, 20, label );
forceSize( 100, 20, valField );
valuePane.add( valField );
}
public JComponent makeCityPanel( ){
//JPanel labelPane = new JPanel( new GridLayout(0,1) );
//JPanel valuePane = new JPanel( new GridLayout(0,1) );
JPanel labelPane = new JPanel( ); labelPane.setLayout( new BoxLayout( labelPane, BoxLayout.Y_AXIS ) );
JPanel valuePane = new JPanel( ); valuePane.setLayout( new BoxLayout( valuePane, BoxLayout.Y_AXIS ) );
//panel.setLayout(new GridBagLayout());
//panel.setLayout(new GridBagLayout());
name_field = new JTextField( );
addLabeledBox( "name", name_field, labelPane, valuePane );
ix_field = new JFormattedTextField( NumberFormat.getNumberInstance() );
addLabeledBox( "ix", ix_field, labelPane, valuePane);
iy_field = new JFormattedTextField( NumberFormat.getNumberInstance() );
addLabeledBox( "iy", iy_field, labelPane, valuePane);
factorySpace_field = new JFormattedTextField( NumberFormat.getNumberInstance() );
addLabeledBox( "FactorySpace", factorySpace_field, labelPane, valuePane);
storeSpace_field = new JFormattedTextField( NumberFormat.getNumberInstance() );
addLabeledBox( "StoreSapce", storeSpace_field, labelPane, valuePane );
//JScrollPane cityPanel = new JScrollPane( );
JPanel cityPanel = new JPanel(new GridLayout(1,0));
cityPanel.add( labelPane );
cityPanel.add( valuePane );
cityPanel.setSize( 100 , 100 );
return cityPanel;
}
However, I have feeling that this is not the correct way. ( Also here they say that it is bad ).
So is there a better way?