タイトル
TOPJavaSwingJToggleButton → This Page

JToggleButton@Swing サンプル03

概要

Java - Swing - JToggleButton のサンプルです。
・余白を設定
・画像を設定
・画像と文字の余白を設定

解説

トグルボタン1はボタンと文字列の間の余白を大きめに設定、
トグルボタン2は画像表示、
トグルボタン3は画像と文字列を表示
トグルボタン4は画像と文字列を表示し、画像と文字列の余白を大きめに設定しています。

サンプルイメージ

サンプル画像


サンプルソース

import java.awt.Color;
import java.awt.Insets;

import javax.swing.ImageIcon;
import javax.swing.JToggleButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

/**
 * JToggleButton サンプル03
 * ・余白を設定
 * ・画像を設定
 * ・画像と文字の余白を設定
 * 
 * @author みっちー
 */
public class JToggleButton03 extends JFrame {
	
	private static final long serialVersionUID = 1L;
	
	/**
	 * 開始メソッド
	 * 
	 * @param args	パラメータ
	 */
	public static void main(String[] args) {
		JToggleButton03 frame = new JToggleButton03();
		
		// 閉じるボタンをクリックされた場合の動作を設定
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		// ウインドウのタイトルを設定
		frame.setTitle("JToggleButton サンプル03");
		
		// フレームの X座標、Y座標、幅、高さを設定
		frame.setBounds(100, 200, 400, 150);
		
		// フレームを表示(これをしないと透明のフレームが立ち上がってしまう)
		frame.setVisible(true);
	}
	
	/**
	 * コンストラクタ
	 */
	public JToggleButton03() {
		// パネルを作成
		JPanel panelBase = new JPanel();
		
		// トグルボタンを作成
		JToggleButton tbutton1 = new JToggleButton("トグルボタン1");
		JToggleButton tbutton2 = new JToggleButton(new ImageIcon("./img/java.gif"));
		JToggleButton tbutton3 = new JToggleButton("トグルボタン3", new ImageIcon("./img/java.gif"));
		JToggleButton tbutton4 = new JToggleButton("トグルボタン4", new ImageIcon("./img/java.gif"));
		
		// 余白を設定
		tbutton1.setMargin(new Insets(15, 15, 15, 15));
		
		// 画像と文字の余白を設定
		tbutton4.setIconTextGap(50);
		
		// 分かりやすいように背景色を設定
		tbutton1.setBackground(Color.LIGHT_GRAY);
		tbutton2.setBackground(Color.LIGHT_GRAY);
		tbutton3.setBackground(Color.LIGHT_GRAY);
		tbutton4.setBackground(Color.LIGHT_GRAY);
		
		// トグルボタンを追加
		panelBase.add(tbutton1);
		panelBase.add(tbutton2);
		panelBase.add(tbutton3);
		panelBase.add(tbutton4);
		
		// パネルを追加
		getContentPane().add(panelBase);
	}
}

サンプルソースのダウンロード

ソースのダウンロード(Eclipse用のプロジェクトファイルも同梱)

更新履歴

2016/05/13 Windows 8.1 + Java 7 環境で全体を見直し
2008/01/23 新規作成


TOPJavaSwingJToggleButton → This Page