コンポーネントの最小サイズを変更する

広告

コンポーネントが本来持っているサイズに対して水平方向及び垂直方向のパディングを設定しコンポーネントの最小サイズを変更する方法を確認します。コンポーネントは本来のサイズにこのフィールドで設定した値を加えた値がが最小のサイズとなります。

コンポーネントのパディングを設定するには「ipadx」フィールド及び「ipady」フィールドに設定します。

コンポーネントの内側のパディング、つまりコンポーネントの最小幅に追加する
領域の値を指定します。コンポーネントの幅は、少なくともその最小幅に ipadx
ピクセルを足したものです。

デフォルト値は 0 です。
コンポーネントの内側のパディング、つまりコンポーネントの最小の高さに追
加する領域の値を指定します。コンポーネントの高さは、少なくともその最小
の高さに ipady ピクセルを足したものです。

デフォルト値は 0 です。

水平方向及び垂直方向の追加するパディングの大きさをint型の値で指定します。単位はピクセルです。

実際の使い方は次のようになります。

JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());

JButton button1 = new JButton("button1");
JButton button2 = new JButton("button2");

GridBagConstraints gbc = new GridBagConstraints();

gbc.gridx = 0;
gbc.gridy = 0;
gbc.ipadx = 5;
gbc.ipady = 5;
layout.setConstraints(button1, gbc);

gbc.gridx = 1;
gbc.gridy = 0;
gbc.ipadx = 0;
gbc.ipady = 0;
layout.setConstraints(button2, gbc);

p.add(button1);
p.add(button2);

サンプルプログラム

では簡単なサンプルを作成して試してみます。

GridBagLayoutTest8.java

import javax.swing.*;
import java.awt.Font;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.BorderLayout;

public class GridBagLayoutTest8 extends JFrame{

  public static void main(String[] args){
    GridBagLayoutTest8 frame = new GridBagLayoutTest8();

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setBounds(10, 10, 300, 200);
    frame.setTitle("タイトル");
    frame.setVisible(true);
  }

  GridBagLayoutTest8(){
    GridBagLayout layout = new GridBagLayout();
    JPanel p = new JPanel();
    p.setLayout(layout);

    GridBagConstraints gbc = new GridBagConstraints();

    JButton button1 = new JButton("Google");

    gbc.gridx = 0;
    gbc.gridy = 0;
    gbc.gridheight = 2;
    gbc.ipadx = 10;
    layout.setConstraints(button1, gbc);

    JButton button2 = new JButton("Yahoo!");
    button2.setFont(new Font("Arial", Font.PLAIN, 30));

    gbc.gridx = 1;
    gbc.gridy = 0;
    gbc.gridheight = 1;
    gbc.ipadx = 0;
    gbc.ipady = 20;
    layout.setConstraints(button2, gbc);

    JButton button3 = new JButton("MSN");

    gbc.gridx = 1;
    gbc.gridy = 1;
    gbc.ipady = 0;
    layout.setConstraints(button3, gbc);

    p.add(button1);
    p.add(button2);
    p.add(button3);

    getContentPane().add(p, BorderLayout.CENTER);
  }
}

上記をコンパイルした後で実行すると次のように表示されます。

GridBagLayoutでコンポーネントの最小サイズを変更する

今回は左側のコンポーネントは水平方向に10ピクセル、右上のコンポーネントは垂直方向に20ピクセル、パディングを設定しています。設定したパディングの大きさだけコンポーネントのサイズは大きくなっています。

下記は同じ設定で「ipadx」フィールド及び「ipady」フィールドが「0」の場合です。見比べてみて下さい。

GridBagLayoutでコンポーネントの最小サイズを変更する

( Written by Tatsuo Ikura )

Profile
profile_img

著者 / TATSUO IKURA

プログラミングや開発環境構築の解説サイトを運営しています。