TOP →
Java →
Swing →
JButton → This Page
JButton@Swing サンプル10
概要
Java -
Swing -
JButton のサンプルです。
・クリックイベント(方法2)
解説
クリックイベントを実現するには ActionListener を implements したクラスにする必要があります。
ActionListener を implements すると、actionPerformed メソッドを実装する必要があります。
このメソッドにイベントの処理内容を記述します。
また、addActionListener メソッドでボタンからのイベントが受け取れるようにアクションリスナーの追加を行います。
今回のサンプルでは各ボタンにアクションコマンドを設定し、
アクションコマンドによってどのボタンがクリックかを判定しています。
サンプルイメージ
サンプルソース
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
/**
* JButton サンプル10
* ・クリックイベント(方法3)
*
* @author みっちー
*/
public class JButton10 extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
/** イベント表示テキスト */
JTextField text = null;
/**
* 開始メソッド
*
* @param args パラメータ
*/
public static void main(String[] args) {
JButton10 frame = new JButton10();
// 閉じるボタンをクリックされた場合の動作を設定
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// ウインドウのタイトルを設定
frame.setTitle("JButton サンプル10");
// フレームの X座標、Y座標、幅、高さを設定
frame.setBounds(100, 200, 500, 100);
// フレームを表示(これをしないと透明のフレームが立ち上がってしまう)
frame.setVisible(true);
}
/**
* コンストラクタ
*/
public JButton10() {
// パネルを作成
JPanel panelBase = new JPanel();
// ボタンを作成
JButton button1 = new JButton("AAAAA");
JButton button2 = new JButton("BBBBB");
JButton button3 = new JButton("CCCCC");
// アクションコマンドを設定
button1.setActionCommand("AAA");
button2.setActionCommand("BBB");
button3.setActionCommand("CCC");
// アクションリスナー追加
button1.addActionListener(this);
button2.addActionListener(this);
button3.addActionListener(this);
// テキストを作成
text = new JTextField(20);
// ボタン・テキストを追加
panelBase.add(button1);
panelBase.add(button2);
panelBase.add(button3);
panelBase.add(text);
// パネルを追加
getContentPane().add(panelBase);
}
/**
* アクション
*/
public void actionPerformed(ActionEvent e) {
if ("AAA".equals(e.getActionCommand())) {
text.setText("AAAAA がクリックされた!");
} else if ("BBB".equals(e.getActionCommand())) {
text.setText("BBBBB がクリックされた!");
} else if ("CCC".equals(e.getActionCommand())) {
text.setText("CCCCC がクリックされた!");
}
}
}
サンプルソースのダウンロード
ソースのダウンロード(Eclipse用のプロジェクトファイルも同梱)
更新履歴
2016/05/13 新規作成
TOP →
Java →
Swing →
JButton → This Page