如何为多个JButton创建单个ActionListener [英] How can I create a single ActionListener for multiple JButtons

查看:149
本文介绍了如何为多个JButton创建单个ActionListener的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用MVC创建一个基本计算器。到目前为止,我正在调整一个仅将两个用户输入的值相加的教程。

I'm creating a basic calculator using MVC. So far I'm adapting a tutorial which merely sums two user entered values together.

目前我添加到视图中的每个按钮都有自己的监听器,这没关系。但是,根据教程的控制器每个按钮只有一个ActionListener内部类。这重复了大量的代码。

Currently each button I'm adding to the view has it's own listener, which is ok. However, the controller as per the tutorial has a single ActionListener inner class per button. This repeats a huge amount of code.

如何为所有按下的按钮创建一个ActionListener类,并在按下的按钮的id上使用case语句?

How can I create a single ActionListener class for all buttons pressed, and use a case statement on the id of the button pressed?

在视图中注册oneButton

void oneListener(ActionListener listenForOneButton){    
    oneButton.addActionListener(listenForOneButton);
}    

在Controller内部类中为oneButton实现ActionListener

class oneListener implements ActionListener{
    public void actionPerformed(ActionEvent e){
        int previousNumber, displayNumber = 0;          
        try{
            previousNumber = theView.getPreviousDisplayNumber();
            displayNumber = previousNumber+1;               
            theView.setDisplayNumber(displayNumber);
        }           
        catch(NumberFormatException ex){                
            System.out.println(ex);             
            theView.displayErrorMessage("You Need to Enter Integers");              
        }           
    }
}


推荐答案

public class SingleActionListener implements ActionListener {
    public void initializeButtons() {
        JButton[] buttons = new JButton[4];
        String[] buttonNames = new String[] {"button1", "button2", "button3", "button4"};

        for (int i = 0; i < 4; i++) {
            buttons[i] = new JButton(buttonNames[i]);
        }
    }

    public void addActionListenersToButtons() {
        for (int i = 0; i < 4; i++) {
            buttons[i].addActionListener(this);
        }
    }

    public void actionPerformedd(ActionEvent actionEvent) {
        if (actionEvent.getSource() == buttons[0]) {
            //Do required tasks.
        }

        if (actionEvent.getSource() == buttons[1]) {
            //Do required tasks.
        }

        if (actionEvent.getSource() == buttons[2]) {
            //Do required tasks.
        }

        if (actionEvent.getSource() == buttons[3]) {
            //Do required tasks.
        }
    }
}

这篇关于如何为多个JButton创建单个ActionListener的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆