菜鸟学JAVA之事件

我们通过JFrame可以构建出一个窗体,然而窗体的很多部分还得好好完善,比如说我们想通过点击相关的按钮,标签,来实现相关的功能。而这就需要用到事件。如果我们想完善窗口的布局,让它看上去更加美观。这就需要用到布局。而本篇,我们将给大家讲述的是事件的使用。


JAVA中的事件


java中的事件在“java.awt.event”与“javax.swing.event”中,一般我们通过使用java.awt.event就足够了。因为这个包中,有我们所需的ActionListener,MouseListener,MouseMotionListener等。
本文将介绍ActionListener的使用,因为其他事件的使用方法可以举一反三,因此不累述。

事件的使用


由于事件提供的是个接口,所以我们一般得利用接口的使用来来实现。

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;

public class Jframe3 extends JFrame implements ActionListener {
        //通过实现接口来使用ActionListener
	JButton jb1,jb2,jb3;
	JLabel jl1;
	JPanel pan=new JPanel();
	
	Jframe3 (String s){
		super(s);
		this.setSize(200,200);
		this.setLocationRelativeTo(null);
		this.setContentPane(pan);
		
		jb1=new JButton("早上好");               //汉语
		jb1.addActionListener(this);             //加入监听
		jb2=new JButton("Good morning");         //英语
		jb2.addActionListener(this);
		jb3=new JButton("Guten Morgen");         //德语
		jb3.addActionListener(this);
		jl1=new JLabel();
		
		pan.add(jb1);
		pan.add(jb2);
		pan.add(jb3);
		pan.add(jl1);
		
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setVisible(true);
	}
	
	public void actionPerformed (ActionEvent e){
		//重写actionPerformed来实现相应的功能。
		if (e.getSource()==jb1)
			jl1.setText(jb1.getActionCommand());
		if (e.getSource()==jb2)
			jl1.setText(jb2.getActionCommand());
		if (e.getSource()==jb3)
			jl1.setText(jb3.getActionCommand());
	}
	
}
import java.awt.*;
import javax.swing.*;

public class abc {

	public static void main(String[] args) {
		Jframe3 jf =new Jframe3 ("%David_Loman%:早上好");
		
	}

}
我们通过派生一个新的JFrame类,同时使用ActionListener,完成了当我们点击不同按钮时,便签上显示不同的文字。
由此可以看出事件的使用有以下三步:
实现接口
public class Jframe3 extends JFrame implements ActionListener
加入监听
	jb1.addActionListener(this);             //加入监听
重写相关的方法
	public void actionPerformed (ActionEvent e){
		//重写actionPerformed来实现相应的功能。
		if (e.getSource()==jb1)
			jl1.setText(jb1.getActionCommand());
		if (e.getSource()==jb2)
			jl1.setText(jb2.getActionCommand());
		if (e.getSource()==jb3)
			jl1.setText(jb3.getActionCommand());
	}
以上便是事件的使用了。



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章