JOptionPaneクラスの定義とコンストラクタ

広告

JOptionPaneクラスの定義を確認します。クラス図は次のようになっています。

java.lang.Object
  java.awt.Component
    java.awt.Container
      javax.swing.JComponent
        javax.swing.JOptionPane

public class JOptionPane
extends JComponent
implements Accessible

JOptionPaneクラスはJComponentクラスのサブクラスとなっています。JComponentクラスはSwingで用いられる多くのコンポーネントのベースとなっているクラスです。

JOptionPaneクラスのコンストラクタ

JOptionPaneクラスにも多くのコンストラクタが用意されています。

コンストラクタ
JOptionPane()
テストメッセージを含む JOptionPane を生成します。
JOptionPane(Object message)
UI の提供するプレーンメッセージのメッセージ型およびデフォルトのオプションを使用して、メッセージを表示するための JOptionPane のインスタンスを生成します。
JOptionPane(Object message, int messageType)
指定されたメッセージ型およびデフォルトのオプションを使用して、メッセージを表示するための JOptionPane のインスタンスを生成します。
JOptionPane(Object message, int messageType, int optionType)
指定されたメッセージ型およびオプションを使用して、メッセージを表示するための JOptionPane のインスタンスを生成します。
JOptionPane(Object message, int messageType, int optionType, Icon icon)
指定されたメッセージ型、オプション、およびアイコンを使用して、メッセージを表示するための JOptionPane のインスタンスを生成します。
JOptionPane(Object message, int messageType, int optionType, Icon icon, Object[] options)
指定されたメッセージ型、アイコン、およびオプションを使用して、メッセージを表示するための JOptionPane のインスタンスを生成します。
JOptionPane(Object message, int messageType, int optionType, Icon icon, Object[] options, Object initialValue)
指定されたメッセージ型、アイコン、およびオプションを使い、初期状態で選択されているオプションを指定して、メッセージを表示するための JOptionPane のインスタンスを生成します。

7つのコンストラクタが用意されています。コンストラクタではダイアログに表示する文字列やダイアログの種類、ダイアログに表示されるアイコンの種類などによってコンストラクタを使い分けます。

ただしJOptionPaneクラスでは実際にコンストラクタを使ってオブジェクトを作成するのではなく、JOptionPaneクラスで用意されているstaticメソッドを使ってダイアログを作成します。多くのstaticメソッドが用意されており詳細は次のページ以降で見ていきます。

サンプルプログラム

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

JOptionPaneTest1.java

import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.event.*;

public class JOptionPaneTest1 extends JFrame implements ActionListener{

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

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

  JOptionPaneTest1(){
    JButton button = new JButton("dialog");
    button.addActionListener(this);

    JPanel p = new JPanel();
    p.add(button);

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

  public void actionPerformed(ActionEvent e){
    JOptionPane.showMessageDialog(this, "JOptionPane");
  }
}

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

JOptionPaneのサンプル

ボタンをクリックするとダイアログが表示されます。

JOptionPaneのサンプル

( Written by Tatsuo Ikura )

Profile
profile_img

著者 / TATSUO IKURA

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