Java 示例 - 在 Applet 中创建事件监听器 问题描述 如何在 Applet 中创建事件监听器? 解决方案 以下示例演示了如何创建一个基本的 Applet,其中包含用于添加和减去两个数字的按钮。这里使用的方法是 addActionListener() 来监听事件(单击按钮)和 Button() 构造器来创建按钮。 import java.applet.*; import java.awt.event.*; import java.awt.*; public class EventListeners extends Applet implements ActionListener { TextArea txtArea; String Add, Subtract; int i = 10, j = 20, sum = 0, Sub = 0; public void init() { txtArea = new TextArea(10,20); txtArea.setEditable(false); add(txtArea,"center"); Button b = new Button("Add"); Button c = new Button("Subtract"); b.addActionListener(this); c.addActionListener(this); add(b); add(c); } public void actionPerformed(ActionEvent e) { sum = i + j; txtArea.setText(""); txtArea.append("i = "+ i + "\t" + "j = " + j + "\n"); Button source = (Button)e.getSource(); if(source.getLabel() == "Add") { txtArea.append("Sum : " + sum + "\n"); } if(i > j) { Sub = i - j; } else { Sub = j - i; } if(source.getLabel() == "Subtract") { txtArea.append("Sub : " + Sub + "\n"); } } } 复制 结果 上面的代码示例将在启用 java 的 Web 浏览器中产生以下结果。 View in Browser. 复制