java实用教程——组件及事件处理——ActionEvent事件
ActionEvent类中的方法: ActionEvent类有如下常用方法 public Object getSource() 可以获取发生ActionEvent事件的事件源对象的引用
public String getActionCommand() 和该事件相关的一个“命令”字符串,对于文本框,当发生ActionEvent事件是,默认的“命令”字符串是文本框中的文本
主类
public class Example9_6 { public static void main(String args[]) { WindowActionEvent win=new WindowActionEvent(); win.setBounds(100,100,310,260); win.setTitle("处理ActionEvent事件"); } }
实现监视器的类
import java.awt.*; import java.awt.event.*; public class ReaderListen implements ActionListener{ public void actionPerformed(ActionEvent e) { String str = e.getActionCommand(); System.out.println(str+":"+str.length()); } }
import java.awt.*; import javax.swing.*; import java.awt.event.*; public class WindowActionEvent extends JFrame { TextField text; ActionListener listener; public WindowActionEvent() { setLayout(new FlowLayout()); init(); setVisible(true); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); } void init() { text = new TextField(10); listener = new ReaderListen(); text.addActionListener(listener); this.add(text); } }
public class Example9_7 { public static void main(String args[]) { WindowActionEvent win=new WindowActionEvent(); PoliceListen police = new PoliceListen();//创建监视器 win.setMyCommandListener(police);//窗口组合监视器 win.setBounds(100,100,310,260); win.setTitle("处理ActionEvent事件"); } }
import javax.swing.*; import java.awt.event.*;//实现这些事件处理必须要有这个包event public interface MyCommandListener extends ActionListener{ public void setTextField(JTextField text); public void setJTextArea(JTextArea area); }
import javax.swing.*; import java.awt.event.*; public class PoliceListen implements MyCommandListener{ JTextField textinput; JTextArea textshow; public void setTextField(JTextField text) { textinput=text; } public void setJTextArea(JTextArea area) { textshow=area; } public void actionPerformed(ActionEvent e) { String str = textinput.getText(); textshow.append(str+":"+str.length()+" "); } }
import java.awt.*; import javax.swing.*; import java.awt.event.*; public class WindowActionEvent extends JFrame { JTextField text;//文本区 JTextArea textshow;//用于输出的文本框 JButton button; MyCommandListener listener;//监视器 public WindowActionEvent() { init(); setVisible(true); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); } void init() { setLayout(new FlowLayout());//设置布局 text = new JTextField(10); textshow = new JTextArea(9,30); button = new JButton("确定"); this.add(text); this.add(new JScrollPane(textshow));//设置为滚动窗格 this.add(button); } void setMyCommandListener(MyCommandListener listener) { this.listener=listener; listener.setTextField(text); listener.setJTextArea(textshow); text.addActionListener(listener); //text是事件源,listener是监视器 button.addActionListener(listener); //button是事件源,listener是监视器 } }
下一篇:
浏览器API 文字转语音