TOP →
Java →
Swing →
JButton → This Page
JButton@Swing サンプル08
概要
Java -
Swing -
JButton のサンプルです。
・クリックイベント(方法1)
解説
クリックイベントを実現するには 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 サンプル08
* ・クリックイベント(方法1)
*
* @author みっちー
*/
public class JButton08 extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
/** イベント表示テキスト */
JTextField text = null;
/**
* 開始メソッド
*
* @param args パラメータ
*/
public static void main(String[] args) {
JButton08 frame = new JButton08();
// 閉じるボタンをクリックされた場合の動作を設定
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// ウインドウのタイトルを設定
frame.setTitle("JButton サンプル08");
// フレームの X座標、Y座標、幅、高さを設定
frame.setBounds(100, 200, 500, 100);
// フレームを表示(これをしないと透明のフレームが立ち上がってしまう)
frame.setVisible(true);
}
/**
* コンストラクタ
*/
public JButton08() {
// パネルを作成
JPanel panelBase = new JPanel();
// ボタンを作成
JButton button1 = new JButton("AAAAA");
JButton button2 = new JButton("BBBBB");
JButton button3 = new JButton("CCCCC");
// アクションリスナー追加
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 (e.getActionCommand().equals("AAAAA")) {
text.setText("AAAAA がクリックされた!");
} else if (e.getActionCommand().equals("BBBBB")) {
text.setText("BBBBB がクリックされた!");
} else if (e.getActionCommand().equals("CCCCC")) {
text.setText("CCCCC がクリックされた!");
}
}
}
サンプルソースのダウンロード
ソースのダウンロード(Eclipse用のプロジェクトファイルも同梱)
更新履歴
2016/05/13 Windows 8.1 + Java 7 環境で全体を見直し
2008/01/17 新規作成
TOP →
Java →
Swing →
JButton → This Page