下拉菜单 和 选择框 触发ItemListener事件
//Inner class 事件处理例一
import java.awt.*;
import java.awt.event.*;
import java.net.PortUnreachableException;
import javax.swing.*;class WindowOperator extends JFrame
{
JTextField inputNumber1, inputNumber2; // 输入框JComboBox choiceFuhao; // 下拉菜单JTextArea textshow; // 输出框JButton button; // 确认按钮OperatorListener operator; // 监视 下拉菜单的监视器ComputerListener computer; // 监视 ActionEvent 的监视器,也就是按钮public WindowOperator(String s){
init(s);setVisible(true);setDefaultCloseOperation(EXIT_ON_CLOSE);}public void init(String s){
setLayout(new FlowLayout());setTitle(s);setBounds(100, 100, 390, 360);// 实例化组件inputNumber1 = new JTextField(5);inputNumber2 = new JTextField(5);choiceFuhao = new JComboBox();button = new JButton("计算");choiceFuhao.addItem("选择计算符号:");String [] a = {
"+", "-", "*", "/"};for(int i = 0; i < a.length; i++)choiceFuhao.addItem(a[i]);textshow = new JTextArea(9, 30);operator = new OperatorListener();computer = new ComputerListener();// 输入文本监视器operator.setJComBox(choiceFuhao); // 设置下拉菜单内容operator.setWorkTogether(computer); // 设置监听器// 按钮和输出文本监视器computer.setJTexFiled1(inputNumber1); // 设置数字文本内容computer.setJTexFiled2(inputNumber2);computer.setJTextArea(textshow);// 注册符号的监听器choiceFuhao.addItemListener(operator);// 注册计算按钮的监视器button.addActionListener(computer);// 添加组件add(inputNumber1);add(choiceFuhao);add(inputNumber2);add(button);add(textshow);}// 实例化OperatorListener,下拉菜单的监视器public class OperatorListener implements ItemListener{
JComboBox choice;ComputerListener workTogether;public void setJComBox(JComboBox box) {
choice = box;} // 设置下拉菜单内容public void setWorkTogether(ComputerListener computer) {
workTogether = computer;} // 设置监听器public void itemStateChanged(ItemEvent e){
String fuhao = choice.getSelectedItem().toString(); // getSelectedItem返回的是对象workTogether.setFuhao(fuhao);}}// 实例化ComputerListener,按钮的监视器private class ComputerListener implements ActionListener{
JTextField inpterNumber1, inpterNumber2;JTextArea textshow;String fuhao ;public void setJTexFiled1(JTextField t) {
inputNumber1 = t;}public void setJTexFiled2(JTextField t) {
inputNumber2 = t;}public void setJTextArea(JTextArea t) {
textshow = t; }public void setFuhao(String s) {
fuhao = s;}public void actionPerformed(ActionEvent e){
//将文本中的字符串转为doubledouble num1 = Double.valueOf(inputNumber1.getText());double num2 = Double.valueOf(inputNumber2.getText());double sum = 0;// 计算if (fuhao.equals("+")) {
sum = num1 + num2;}else if(fuhao.equals("-")) {
sum = num1 - num2;}else if(fuhao.equals("*")) {
sum = num1 * num2;}else if(fuhao.equals("/")) {
sum = num1 / num2;}String res = String.format("%.3f", sum);// 将结果转为字符串输出textshow.append(num1 + " " + fuhao + " " + num2 + " = " + res + "\n");}}
}//主类
public class test
{
public static void main(String args[]){
WindowOperator win = new WindowOperator("简单计算器");}
}
实现ItemListener
接口,覆盖函数itemStateChanged
,传入参ItemEvent