When I use the code below it doesn't alter the size at all, it still fills the area in the grid.
JPanel displayPanel = new JPanel(new GridLayout(4, 2));
JTextField titleText = new JTextField("title");
displayPanel.add(titleText);
titleText.setSize(200, 24);
This question is related to
java
resize
size
jframe
jtextfield
From the api on GridLayout:
The container is divided into equal-sized rectangles, and one component is placed in each rectangle.
Try using FlowLayout or GridBagLayout for your set size to be meaningful. Also, @Serplat is correct. You need to use setPreferredSize( Dimension ) instead of setSize( int, int ).
JPanel displayPanel = new JPanel();
// JPanel displayPanel = new JPanel( new GridLayout( 4, 2 ) );
// JPanel displayPanel = new JPanel( new BorderLayout() );
// JPanel displayPanel = new JPanel( new GridBagLayout() );
JTextField titleText = new JTextField( "title" );
titleText.setPreferredSize( new Dimension( 200, 24 ) );
// For FlowLayout and GridLayout, uncomment:
displayPanel.add( titleText );
// For BorderLayout, uncomment:
// displayPanel.add( titleText, BorderLayout.NORTH );
// For GridBagLayout, uncomment:
// displayPanel.add( titleText, new GridBagConstraints( 0, 0, 1, 1, 1.0,
// 1.0, GridBagConstraints.CENTER, GridBagConstraints.NONE,
// new Insets( 0, 0, 0, 0 ), 0, 0 ) );
With a BorderLayout you need to use setPreferredSize
instead of setSize
Try to play with
setMinSize()
setMaxSize()
setPreferredSize()
These method are used by layout when it decide what should be the size of current element. The layout manager calls setSize() and actually overrides your values.
Any component added to the GridLayout will be resized to the same size as the largest component added. If you want a component to remain at its preferred size, then wrap that component in a JPanel and then the panel will be resized:
JPanel displayPanel = new JPanel(new GridLayout(4, 2));
JTextField titleText = new JTextField("title");
JPanel wrapper = new JPanel( new FlowLayout(0, 0, FlowLayout.LEADING) );
wrapper.add( titleText );
displayPanel.add(wrapper);
//displayPanel.add(titleText);
Source: Stackoverflow.com