菜鳥學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());
	}
以上便是事件的使用了。



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