在Java中使用具有相同标签的多个JButton [英] Using multiple JButtons with the same label in Java

查看:190
本文介绍了在Java中使用具有相同标签的多个JButton的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的项目中有两个带有 +标签的按钮。调用actionPerformed()方法时,它将基于标签调用特定的方法。如何区分带有相同标签的两个JButton?

I have two buttons in my project that both have a "+" label. When the actionPerformed() method is called, it calls a specific method based on the label. How can I distiguish between two JButtons with the same label? Is there a better way to do this then how I've done it?

这是按钮的定义:

JButton keypadPlus1 = new JButton(" + ");
JButton keypadMinus1 = new JButton(" - ");
JButton keypadPlus2 = new JButton("+");
JButton keypadMinus2 = new JButton("-");

为按钮添加ActionListener:

Adding the ActionListeners for the buttons:

keypadPlus1.addActionListener(backEnd);
keypadPlus2.addActionListener(backEnd);
keypadMinus1.addActionListener(backEnd);
keypadMinus2.addActionListener(backEnd);

该操作在后端执行@Override:

The actionPerformed @Override in the backEnd:

public void actionPerformed (ActionEvent event) {
        String command = event.getActionCommand();
        if (command.equals("+")) {
            calcLifePoints(command);
        }
        if (command.equals("-")) {
            calcLifePoints(command);
        }
        if (command.equals(" + ")) {
            calcLifePoints(command);
        }
        if (command.equals(" - ")) {
            calcLifePoints(command);
        }

    }


推荐答案

相反,

public void actionPerformed (ActionEvent event) {
        String command = event.getActionCommand();
        if (command.equals("+")) {
            calcLifePoints(command);
        }
        if (command.equals("-")) {
            calcLifePoints(command);
        }
        if (command.equals(" + ")) {
            calcLifePoints(command);
        }
        if (command.equals(" - ")) {
            calcLifePoints(command);
        }

    }

使用这种方式

public void actionPerformed (ActionEvent event) {
        Object command = event.getSource();
        if (command.equals(keypadPlus1)) {
            calcLifePoints(event.getActionCommand());
        }
        if (command.equals(keypadMinus1)) {
            calcLifePoints(event.getActionCommand());
        }
        if (command.equals(keypadPlus2)) {
            calcLifePoints(event.getActionCommand());
        }
        if (command.equals(keypadMinus2)) {
            calcLifePoints(event.getActionCommand());
        }

    }

这篇关于在Java中使用具有相同标签的多个JButton的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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