以下のコードを使用しても、サイズはまったく変更されませんが、グリッド内の領域が埋められます。
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から:
コンテナは同じサイズの長方形に分割され、各長方形に1つのコンポーネントが配置されます。
設定したサイズを意味のあるものにするために、FlowLayoutまたはGridBagLayoutを使用してみてください。また、@Serplatは正しいです。setSize(int、int)の代わりにsetPreferredSize(Dimension)を使用する必要があります。
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 ) );
BorderLayoutsetPreferredSize
では、代わりにを使用する必要があります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()を呼び出し、実際に値を上書きします。