タイトル
TOPJavaSwingJOptionPane → This Page

JOptionPane@Swing サンプル03

概要

Java - Swing - JOptionPane のサンプルです。
・色々なメッセージダイアログ

解説

メッセージ1は通常の文字列をメッセージとして表示、
メッセージ2はラベルをメッセージとして表示、
メッセージ3はアイコン非表示、
メッセージ4は自前のアイコンを表示しています。

サンプルイメージ

メイン画面
サンプル画像

メッセージ1
サンプル画像

メッセージ2
サンプル画像

メッセージ3
サンプル画像

メッセージ4
サンプル画像


サンプルソース

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

/**
 * JOptionPane サンプル03
 * ・色々なメッセージダイアログ
 * 
 * @author みっちー
 */
public class JOptionPane03 extends JFrame implements ActionListener {
	
	private static final long serialVersionUID = 1L;
	
	/**
	 * 開始メソッド
	 * 
	 * @param args	パラメータ
	 */
	public static void main(String[] args) {
		JOptionPane03 frame = new JOptionPane03();
		
		// 閉じるボタンをクリックされた場合の動作を設定
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		// ウインドウのタイトルを設定
		frame.setTitle("JOptionPane サンプル03");
		
		// フレームの X座標、Y座標、幅、高さを設定
		frame.setBounds(100, 200, 420, 100);
		
		// フレームを表示(これをしないと透明のフレームが立ち上がってしまう)
		frame.setVisible(true);
	}
	
	/**
	 * コンストラクタ
	 */
	public JOptionPane03() {
		// パネルを作成
		JPanel panelBase = new JPanel();
		
		// ボタンを作成
		JButton button1 = new JButton("Message1");
		JButton button2 = new JButton("Message2");
		JButton button3 = new JButton("Message3");
		JButton button4 = new JButton("Message4");
		
		// アクションコマンドを設定
		button1.setActionCommand("Message1");
		button2.setActionCommand("Message2");
		button3.setActionCommand("Message3");
		button4.setActionCommand("Message4");
		
		// アクションリスナー追加
		button1.addActionListener(this);
		button2.addActionListener(this);
		button3.addActionListener(this);
		button4.addActionListener(this);
		
		// ボタンを追加
		panelBase.add(button1);
		panelBase.add(button2);
		panelBase.add(button3);
		panelBase.add(button4);
		
		// パネルを追加
		getContentPane().add(panelBase);
	}
	
	/**
	 * アクション
	 */
	public void actionPerformed(ActionEvent e) {
		if ("Message1".equals(e.getActionCommand())) {
			// 文字列を表示
			JOptionPane.showMessageDialog(this, "Message1");
		} else if ("Message2".equals(e.getActionCommand())) {
			// ラベルを使って表示
			JLabel label = new JLabel("Message2");
			label.setForeground(Color.RED);
			JOptionPane.showMessageDialog(this, label);
		} else if ("Message3".equals(e.getActionCommand())) {
			// タイトルも表示
			JOptionPane.showMessageDialog(this, "Message3", "title3", JOptionPane.PLAIN_MESSAGE);
		} else if ("Message4".equals(e.getActionCommand())) {
			// アイコンも表示
			ImageIcon icon = new ImageIcon("./img/00.png");
			JOptionPane.showMessageDialog(this, "Message4", "title4", JOptionPane.PLAIN_MESSAGE, icon);
		}
	}
}

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

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

更新履歴

2016/08/27 新規作成


TOPJavaSwingJOptionPane → This Page