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

来源:互联网 发布:js bind方法详解 编辑:程序博客网 时间:2024/05/21 09:48

/* * 事件监听与处理  */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事件源");}}}



0 0