没有合适的资源?快使用搜索试试~ 我知道了~
资源推荐
资源详情
资源评论
Java添加事件监听的四种方法代码实例添加事件监听的四种方法代码实例
主要介绍了Java添加事件监听的四种方法代码实例,本文直接给出代码示例,并用注释说明,需要的朋友可以参考
下
Java添加事件的几种方式(转载了codebrother的文章,做了稍微的改动):
/**
* Java事件监听处理——自身类实现ActionListener接口,作为事件监听器
*
* @author codebrother
*/
class EventListener1 extends JFrame implements ActionListener {
private JButton btBlue, btDialog;
public EventListener1() {
setTitle("Java GUI 事件监听处理");
setBounds(100, 100, 500, 350);
setLayout(new FlowLayout());
btBlue = new JButton("蓝色");
btDialog = new JButton("弹窗");
// 将按钮添加事件监听器
btBlue.addActionListener(this);
btDialog.addActionListener(this);
add(btBlue);
add(btDialog);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
// ***************************事件处理***************************
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btBlue) {
Container c = getContentPane();
c.setBackground(Color.BLUE);
}
else if (e.getSource() == btDialog) {
JDialog dialog = new JDialog();
dialog.setBounds(300, 200, 400, 300);
dialog.setVisible(true);
}
}
}
/**
* Java事件监听处理——内部类处理
*
* @author codebrother
*/
class EventListener3 extends JFrame {
private JButton btBlue, btDialog;
// 构造方法
public EventListener3() {
setTitle("Java GUI 事件监听处理");
setBounds(100, 100, 500, 350);
setLayout(new FlowLayout());
btBlue = new JButton("蓝色");
btDialog = new JButton("弹窗");
// 添加事件监听器对象(面向对象思想)
btBlue.addActionListener(new ColorEventListener());
btDialog.addActionListener(new DialogEventListener());
add(btBlue);
add(btDialog);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
// 内部类ColorEventListener,实现ActionListener接口
class ColorEventListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
Container c = getContentPane();
c.setBackground(Color.BLUE);
weixin_38684743
- 粉丝: 6
- 资源: 960
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功
- 1
- 2
前往页