自定义按钮添加事件监听器
对象.addActionListener(this);
对象.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.out.println("单击了按键1");
}
});
例子:
package 界面编程7;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextArea;
public class QQ extends JFrame implements ActionListener{
public QQ() {
this.setTitle("界面");
this.setBounds(100, 100, 300, 400);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setVisible(true);
FlowLayout layout = new FlowLayout();
this.setLayout(layout);
JButton jb1 = new JButton("1");
JButton jb2 = new JButton("2");
JButton jb3 = new JButton("3");
this.add(jb1);
this.add(jb2);
this.add(jb3);
jb1.addActionListener(this);
jb1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.out.println("单击了按键1");
}
});
jb2.addActionListener(this);
jb2.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.out.println("单击了按键2");
}
});
jb3.addActionListener(this);
jb3.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.out.println("单击了按键3");
}
});
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
System.out.println("鼠标点击了");
}
}
package 界面编程7;
public class QQmain {
public static void main(String[] args) {
// TODO Auto-generated method stub
QQ qq = new QQ();
}
}
测试结果: