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
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);
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.
Source: Stackoverflow.com