当我使用下面的代码时,它根本不会改变大小,它仍然会填充网格中的区域。
JPanel displayPanel = new JPanel(new GridLayout(4, 2));
JTextField titleText = new JTextField("title");
displayPanel.add(titleText);
titleText.setSize(200, 24);
当我使用下面的代码时,它根本不会改变大小,它仍然会填充网格中的区域。
JPanel displayPanel = new JPanel(new GridLayout(4, 2));
JTextField titleText = new JTextField("title");
displayPanel.add(titleText);
titleText.setSize(200, 24);
从 GridLayout 上的 api:
容器被分成大小相等的矩形,每个矩形中放置一个组件。
尝试使用 FlowLayout 或 GridBagLayout 使您的设置大小有意义。此外,@Serplat 是正确的。您需要使用setPreferredSize( Dimension )而不是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 ) );
使用 BorderLayout 您需要使用setPreferredSize
而不是setSize
添加到 GridLayout 的任何组件都将调整为与添加的最大组件相同的大小。如果您希望组件保持其首选大小,则将该组件包装在 JPanel 中,然后面板将调整大小:
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);
试着玩
setMinSize()
setMaxSize()
setPreferredSize()
布局在决定当前元素的大小时会使用这些方法。布局管理器调用 setSize() 并实际覆盖您的值。