TOP →
Java →
Swing →
JRadioButton → This Page
JRadioButton@Swing サンプル03
概要
Java -
Swing -
JRadioButton のサンプルです。
・余白を設定
・画像を設定
・画像と文字の余白を設定
解説
ラジオボタン1はボタンと文字列の間の余白を大きめに設定、
ラジオボタン2は画像表示、
ラジオボタン3は画像と文字列を表示
ラジオボタン4は画像と文字列を表示し、画像と文字列の余白を大きめに設定しています。
単純に画像を設定するとラジオボタンの選択状態がわからなくなるので、
実際には別ページで解説している「選択画像を設定」もしてあげるのが一般的です。
サンプルイメージ
サンプルソース
import java.awt.Color;
import java.awt.Insets;
import javax.swing.ImageIcon;
import javax.swing.JRadioButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
/**
* JRadioButton サンプル03
* ・余白を設定
* ・画像を設定
* ・画像と文字の余白を設定
*
* @author みっちー
*/
public class JRadioButton03 extends JFrame {
private static final long serialVersionUID = 1L;
/**
* 開始メソッド
*
* @param args パラメータ
*/
public static void main(String[] args) {
JRadioButton03 frame = new JRadioButton03();
// 閉じるボタンをクリックされた場合の動作を設定
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// ウインドウのタイトルを設定
frame.setTitle("JRadioButton サンプル03");
// フレームの X座標、Y座標、幅、高さを設定
frame.setBounds(100, 200, 400, 150);
// フレームを表示(これをしないと透明のフレームが立ち上がってしまう)
frame.setVisible(true);
}
/**
* コンストラクタ
*/
public JRadioButton03() {
// パネルを作成
JPanel panelBase = new JPanel();
// ラジオボタンを作成
JRadioButton radio1 = new JRadioButton("ラジオボタン1");
JRadioButton radio2 = new JRadioButton(new ImageIcon("./img/java.gif"));
JRadioButton radio3 = new JRadioButton("ラジオボタン3", new ImageIcon("./img/java.gif"));
JRadioButton radio4 = new JRadioButton("ラジオボタン4", new ImageIcon("./img/java.gif"));
// 余白を設定
radio1.setMargin(new Insets(15, 15, 15, 15));
// 画像と文字の余白を設定
radio4.setIconTextGap(50);
// 分かりやすいように背景色を設定
radio1.setBackground(Color.LIGHT_GRAY);
radio2.setBackground(Color.LIGHT_GRAY);
radio3.setBackground(Color.LIGHT_GRAY);
radio4.setBackground(Color.LIGHT_GRAY);
// ラジオボタンを追加
panelBase.add(radio1);
panelBase.add(radio2);
panelBase.add(radio3);
panelBase.add(radio4);
// パネルを追加
getContentPane().add(panelBase);
}
}
サンプルソースのダウンロード
ソースのダウンロード(Eclipse用のプロジェクトファイルも同梱)
更新履歴
2016/05/13 Windows 8.1 + Java 7 環境で全体を見直し
2008/01/23 新規作成
TOP →
Java →
Swing →
JRadioButton → This Page