java - 如何为相同的按钮制作 Action 命令

标签 java swing jbutton actionlistener

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

    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);     
        }

        }
    });

我想知道我是否可以为这个按钮制作一个 Action 命令,这样我就不必在我的程序中重复这段代码。我只需要调用 buttonaction(e) 之类的函数。我不习惯创建 Action 命令,但我以前使用过它,但仅用于附加文本。我不确定如何使用这样的功能来做到这一点。是否可以?还是有更有效的方法来做到这一点?

最佳答案

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

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);

关于java - 如何为相同的按钮制作 Action 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24989527/

相关文章:

Java 监听按钮和键盘点击

java - 如何将面板发送到内部框架的背面?

Java,输出未显示?

java - 重新绘制图形问题

java - JTable 与 JScrollpane 中的 JPanel 列表

java - 如何更改 JFrame 中组件的尺寸

java - 更改 JButtons 背景的最佳方法

java - 使用 Java nio 写入文件元数据的问题

java - 引用了未解析的外部符号 __imp__JNI_CreateJavaVM@12

java - 我可以将 CSS 应用于 swing 文本组件吗?