JAVA图形界面中的事件处理

在JAVA应用程序或者Applet运行时,如果用户进行某个操作,例如单机鼠标键或者输入字符,程序应当做出适当响应。
那举个例子来说,当我们点击某个按钮,会出现一个按钮事件,那么这个就是按钮的事件处理;
在这里呢,我们还是通过举例子来说明JAVA的事件处理;
在这里插入图片描述
首先我们在容器中加入一个按钮,我们给这个按钮添加事件处理;

public static void main(String[] args) {
	JFrame frame=new JFrame("event");
	JButton b1;
	b1=new JButton("b1");
	frame.getContentPane().setLayout(new FlowLayout());
	frame.add(b1);
	frame.setSize(300,100);
	frame.setVisible(true);


}

运行后的话;
在这里插入图片描述

现在我想点击这个按钮,在控制台有字符串输出;

首先我们要新建一个类;
加上接口并且重写其中方法(固定的);

package array;
import java.awt.event.*;
public class ButtonHandler implements ActionListener{
	public void actionPerformed(ActionEvent e){
		System.out.println("点击了按钮");
	}

}

当然还要加上头文件;

然后回到主函数加上一行代码;

b1.addActionListener(new ButtonHandler());

就完全可以了;

public static void main(String[] args) {
	JFrame frame=new JFrame("event");
	JButton b1;
	b1=new JButton("b1");
	frame.getContentPane().setLayout(new FlowLayout());
	frame.add(b1);
	b1.addActionListener(new ButtonHandler());
	frame.setSize(300,100);
	frame.setVisible(true);


}

然后我们运行看一下效果;
在这里插入图片描述
是不是很简单;

在这里插入图片描述

然后介绍第二种方法;

我们直接及新建一个类让他继承与JBtton并且写上他的接口;
写好构造方法,还有重写的actionPerformed方法;

import java.awt.event.*;

import javax.swing.*;

public class Mybutton extends JButton implements ActionListener{
	public Mybutton(String str) {
		super(str);
		this.addActionListener(this);
	}
	@Override
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
		System.out.println("点击了按钮");
	}



然后我们的主函数里面,就可以一直用这个按钮了,想用的时候我就建一个,不用再写一个事件处理的类了;

public static void main(String[] args) {
	JFrame frame=new JFrame("event");
	Mybutton b1;
	b1=new Mybutton("b1");
	frame.getContentPane().setLayout(new FlowLayout());
	frame.add(b1);
	b1.addActionListener(new ButtonHandler());
	frame.setSize(300,100);
	frame.setVisible(true);


}

运行效果和刚才的一模一样;

第三种方法,我们不用新建类,直接就在主函数里面写全部的,如果代码不多的话可以这样,但如果代码很多就不建议这样;
直接来代码吧;

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class test {
public static void main(String[] args) {
	JFrame frame=new JFrame("event");
	JButton b1;
	b1=new JButton("b1");
	b1.addActionListener(new ActionListener(){
		@Override
		public void actionPerformed(ActionEvent e) {
			// TODO Auto-generated method stub
			System.out.println("点击了按钮");
		}
	});
	frame.getContentPane().setLayout(new FlowLayout());
	frame.add(b1);
	b1.addActionListener(new ButtonHandler());
	frame.setSize(300,100);
	frame.setVisible(true);


}
}

虽然不用写接口和继承;
但是依旧要写重写的方法;
然后就是格式不要出错;
运行结果和上面的都一样;

到这里三种事件处理的方法就说完了;
OK,结束;
END;
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_46726346/article/details/107102808
今日推荐