如何对相同的按钮发出操作命令 [英] How to make an action command for same buttons

查看:76
本文介绍了如何对相同的按钮发出操作命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我这里只是我的按钮的一小段代码:

I have here just a snip of code for my button:

    up = new JButton(new ImageIcon("more_buttons\\up3.png"));
    up.setBackground(new Color(224,223,227));
    up.setPreferredSize(new Dimension(5,15));
    up.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
        value1000++;    

        if(value1000>0)
        {
            number.setText(value1000+"");
            down.setEnabled(true);
        }
        }
    });


    down = new JButton(new ImageIcon("more_buttons\\down3.png"));
    down.setBackground(new Color(224,223,227));
    down.setPreferredSize(new Dimension(5,15));
    down.setEnabled(false);
    down.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            value1000--;

        if(value1000>0)
        {
            number.setText(value1000+"");
        }
        if(value1000==0)
        {
            number.setText(value1000+"");
            down.setEnabled(false);     
        }

        }
    });

我想知道是否可以为此按钮执行操作命令,这样我就不会在整个程序中重复此代码。我只需要调用 buttonaction(e)之类的函数。我不习惯创建动作命令,但是我以前曾经使用过它,而只是用于附加文本。我不确定如何使用这样的功能。可能吗?还是有更有效的方法?

I'm wondering if I can make an action command for this button so that I won't have to repeat this code throughout my program. I only have to call the function like buttonaction(e) or something like that. I'm not used to creating action command but I have used it before but only for appending text. I'm not sure how to do that with a function like this. Is it possible? Or is there a more efficient way to do this?

推荐答案

您可以添加相同的 ActionListener 到多个按钮:

You can add the same ActionListener to multiple buttons:

ActionListener al = new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        // You can check which button was pressed and act accordingly
        // simply by checking the event source:
        if (e.getSource() == button1)
            System.out.println("Button1 was pressed.");
        else if (e.getSource() == button2)
            System.out.println("Button2 was pressed.");
    }
};

button1.addActionListener(al);
button2.addActionListener(al);

这篇关于如何对相同的按钮发出操作命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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