您的位置:首页 > 编程语言 > Java开发

Java图形界面——事件监听与处理

2017-05-23 08:27 731 查看
/*

* 事件监听与处理

*/

package com.test.tank;

import javax.swing.*;

import javax.swing.border.Border;

import java.awt.*;

import java.awt.event.*;

public class Test2 extends JFrame implements ActionListener{

JPanel jp = null;

JButton jbt1 = null;

JButton jbt2 = null;

public static void main(String[] args) {

Test2 test = new Test2();

}

public Test2(){

jp = new JPanel();

jbt1 = new JButton("红色");

jbt1.addActionListener(this); //注册监听 ; this代表Test2这个类(对象)

jbt1.setActionCommand("red"); //设置命令

jbt2 = new JButton("蓝色");

jbt2.addActionListener(this); //注册监听

jbt2.setActionCommand("blue"); //设置命令

Other other = new Other();

jbt2.addActionListener(other); //让Other类的对象也注册监听jbt2

//添加组件并布局

this.add(jbt1, BorderLayout.WEST);

this.add(jp, BorderLayout.CENTER);

jp.setBackground(Color.black);

this.add(jbt2, BorderLayout.EAST);

this.setSize(300, 200);

this.setTitle("事件监听与处理");

this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

this.setVisible(true);

}

@Override //对事件的处理方法

public void actionPerformed(ActionEvent e) {

if(e.getActionCommand().equals("red")){//命令相同,则执行对应操作

jp.setBackground(Color.red);

}

if(e.getActionCommand().equals("blue")){

jp.setBackground(Color.blue);

}

}

}

/*

* 测试:同一个事件可让多个监听者(对象)

*/

class Other implements ActionListener{

@Override //也必须重写对事件的处理方法

public void actionPerformed(ActionEvent e) {

if(e.getActionCommand().endsWith("blue")){

System.out.println("其他对象也监听必处理了jbt2事件源");

}

}

}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: