我們通過JFrame可以構建出一個窗體,然而窗體的很多部分還得好好完善,比如說我們想通過點擊相關的按鈕,標籤,來實現相關的功能。而這就需要用到事件。如果我們想完善窗口的佈局,讓它看上去更加美觀。這就需要用到佈局。而本篇,我們將給大家講述的是事件的使用。
JAVA中的事件
事件的使用
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());
}
以上便是事件的使用了。