ボタンを表示&動作を与える(JButton&ActionListener)
/*
* ボタンを表示し、クリックすると表示が変更できるクラス
*/
package button;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
public class ShowButton implements ActionListener {
private JFrame frame;
// ボタンを宣言。ボタンはJButtonを使用。
private JButton button1;
private MyPanel panel;
public ShowButton() {
frame = new JFrame();
// ボタンのインスタンスを生成。
// 引数(String)を与えることでボタン名を設定できる。
button1 = new JButton("ボタン1");
panel = new MyPanel();
frame.setTitle("ここにタイトル");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(300, 400, 200, 200);
// nullレイアウトと言い、コンポーネントに指定された位置で
// 表示を行う。
frame.getContentPane().setLayout(null);
frame.getContentPane().add(panel, null);
// ボタンの表示位置を設定
button1.setBounds(50, 110, 100, 40);
// ボタンを押された時のアクションをつける
button1.addActionListener(this);
// ボタンをコンテナーに表示
frame.getContentPane().add(button1);
frame.setVisible(true);
}
public static void main(String args[]) {
new ShowButton();
}
// アクションを処理するメソッド
// この場合は、ボタンを処理する為にしか使っていません。
public void actionPerformed(ActionEvent ae) {
// どのアクションか判別するためにアクションコマンドを
// 確認。(ボタンのアクションコマンドはボタン名)
if( ae.getActionCommand() == "ボタン1" ) {
System.out.println("ボタンをクリックしました");
// 色を変える
panel.changeColor();
// MyPanelを再描画
panel.repaint();
}
}
}
class MyPanel extends JPanel {
private Color col = Color.red;
public MyPanel() {
setBounds(0, 0, 100, 100);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(col);
g.fillRect(0, 0, 100, 100);
}
// ボタンが押された時、色を変える処理
public void changeColor() {
if( col == Color.red ) {
col = Color.blue;
}else{
col = Color.red;
}
}
}