ボタン押下時の処理
●サンプル
import javax.swing.*;
import java.awt.event.*;
import java.awt.BorderLayout;
public class SwingTest extends JFrame implements ActionListener{
JLabel label;
public static void main(String[] args){
SwingTest test = new SwingTest("SwingTest");
test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
test.setVisible(true);
}
SwingTest(String title){
setTitle(title);
setBounds( 10, 10, 300, 200);
label = new JLabel("");
label.setHorizontalAlignment(JLabel.CENTER);
JButton btn1 = new JButton("Button 1");
btn1.addActionListener(this); //アクションリスナー
btn1.setActionCommand("Button 1");
JButton btn2 = new JButton("Button 2");
btn2.addActionListener(this); //アクションリスナー
btn2.setActionCommand("Button 2");
JPanel p = new JPanel(); //パネル
p.add(btn1);パネルボタン追加
p.add(btn2);パネルボタン追加
getContentPane().add(p, BorderLayout.CENTER); //パネルコンテントペイン取得
getContentPane().add(label, BorderLayout.PAGE_END);
}
public void actionPerformed(ActionEvent e){ //ボタン押下時の処理
String cmd = e.getActionCommand();
if (cmd.equals("Button 1")){
label.setText("ボタン1が押されました");
}else if (cmd.equals("Button 2")){
label.setText("ボタン2が押されました");
}
}
}
●実行結果