| ■swingコンポーネント->JButton | |||||
|
ボタンはマウスでクリックするとイベントを発生させることができます。 文字列をアイコンイメージを貼り付けられる四角のボタンです。 |
|
||||
| コンストラクタ(抜粋) | |||||
|
|||||
| メソッド(抜粋) | |||||
|
|||||
|
|
|||||
|
クリックして下さい。 |
|||||
|
JButtonSample1.java |
|||||
| import java.awt.*; | |||||
| import java.awt.event.*; | |||||
| import javax.swing.*; | |||||
| public class JButtonSample1 extends JFrame implements ActionListener{ | ← @ | ||||
| Container contentPane; | |||||
| JLabel lbl1 = new JLabel("名前を入力"); | ← Aインスタンス生成 | ||||
| JTextField txt1 = new JTextField(); | ← Aインスタンス生成 | ||||
| JButton btn1 = new JButton("クリック"); | ← Aインスタンス生成 | ||||
| public JButtonSample1() { | |||||
| super(JButtonSample1); | |||||
| addWindowAdapter(new WindowListener() { | |||||
| public void windowClosing(WindowEvent e) { | |||||
| System.exit(0); | |||||
| } | |||||
| }); | |||||
| contentPane = getContentPane(); | |||||
| setSize(200,60); | |||||
| setLocation(100,100); | |||||
| btn1.addActionListener(this); | ← Bリスナの登録 | ||||
| setLayout(new GridLayout(1,3)); | |||||
| add(lbl1); | ← Cレイアウトに配置 | ||||
| add(txt1); | ← Cレイアウトに配置 | ||||
| add(btn1); | ← Cイアウトに配置 | ||||
| setVisible(true); | |||||
| } | |||||
| pubic void actionPerFormed(ActionEvent e){ | ← D | ||||
| String str = txt1.getText(); | ← E | ||||
| lbl1.setText(str); | ← F | ||||
| } | |||||
| public static void main(String[] args) { | |||||
| JButtonSample1 myClass = new JButtonSample1(); | |||||
| } | |||||
| } | |||||
| @implements
ActionListener JButtonSample1クラスにActionListenerインターフェースを実装します。 |
|||||
| Aインスタンスの生成 ラベル、テキストフィールド、ボタンのそれぞれのインスタンスを生成しています。 |
|||||
| Bボタンにリスナを登録 btn1.addActionListener(this); ボタンがクリックされたときに発生するActionEventをどのオブジェクトが処理するかをaddActionListenerメソッドで 設定します。ここではリスナーオブジェクトはJButtonSample1クラス自身なので、引数にはthisを指定します。 ※リスナーオブジェクトとはActionListenerをimplementsして処理を記述したクラスのこと |
|||||
| Cラベル
とテキストフィールドをそれぞれレイアウトに配置 addメソッドでレイアウトに配置しています。 |
|||||
| Dpubic void
actionPerFormed(ActionEvent e){} ActionListenerをimplementsしたクラスはactionPerFormedメソッドを定義します。 このメソッドの中にボタンが押されたときに行う処理を記述します。 |
|||||
| EString str =
txt1.getText(); String型の変数strにテキストフィールド(txt1)に入力された文字列を取得し代入しています。 |
|||||
| Flbl1.setText(str); 変数strの内容をラベル(lbl1)に設定しています。 |
|||||
| もどる | |||||