第2周:Java事件處理
阿新 • • 發佈:2018-12-29
源程式1simpleEvent.java
import java.applet.*; import java.awt.*; import java.awt.event.*; public class simpleEvent extends Applet implements ActionListener { Label lb; TextField in,out; public void init() { lb = new Label("請輸入你的名字"); in = new TextField(6); //建立輸入文字框 out = new TextField(20); //建立輸出文字框 add(lb); add(in); add(out); in.addActionListener(this); //將文字框註冊給文字事件的監聽者 } public void actionPerformed(ActionEvent e) //執行動作 { out.setText(in.getText() + "歡迎光臨"); } }
執行結果:
源程式2ButtonDemo.java
import java.awt.*; import java.awt.event.*; import java.applet.*; public class ButtonDemo extends Applet implements ActionListener { String msg =""; public void init() { Button yes = new Button("是"); Button no =new Button("否"); Button maybe = new Button("取消"); add(yes); add(no); add(maybe); yes.addActionListener(this); no.addActionListener(this); maybe.addActionListener(this); } public void actionPerformed(ActionEvent e) { String str = e.getActionCommand(); if(str == "是") { msg = "你單擊了按鈕'是'。"; } else if(str == "否") { msg = "你單擊了按鈕'否'。"; } else { msg = "你單擊了按鈕'取消'。"; } repaint(); } public void paint(Graphics g) { g.drawString(msg,6,100); } }
執行結果: