向 1 个 JButton 添加更多鼠标侦听器?

Adding more mouselisteners to 1 JButton?

是否可以向一个 JButton 添加 1 个以上的鼠标侦听器?你知道当我点击按钮时它应该改变颜色和文本,并做一些事情(例如 system.out.println),当我再次点击它时它应该回到之前的状态,并打印其他东西。

我尝试过的:

JButton b = new JButton("First");
b.setBackground(Color.GREEN);
        b.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) 
            {
b.setBackground(Color.RED);
                b.setText("Second");
System.out.println("You've clicked the button");
}
if(b.getModel.isPressed){
b.setBackground(Color.GREEN);
b.setText("Second");
System.out.println("You're back");
}

问题是按钮没有返回到颜色(绿色)和文本的先前状态,我不知道如何处理。

您应该只注册一个监听器,但该监听器会保持一些关于鼠标点击次数的状态。一个简单的 if/else 块将更改操作并更改按钮标签上的文本。

首先,您不应该使用 MouseListener 来执行这些操作,因为更好的侦听器 ActionListener 专门用于与 JButton 和类似实体一起使用以通知程序已按下按钮。

话虽如此,您当然可以向 JButton 添加多个 ActionListener(或 MouseListeners),或者您可以让 ActionListener 根据程序状态更改其行为(通常意味着 class).

您的代码和问题存在一个问题,即我没有看到您何时期望或希望按钮将其颜色改回绿色。如果在一段时间后,让您的 ActionListener 启动一个 Swing 计时器,在 x 毫秒后将按钮的颜色更改回绿色。

编辑:我明白了,您想切换颜色——然后使用您切换的布尔字段或检查按钮的当前颜色,并根据该颜色确定听众的响应。

例子

import java.awt.Color;
import java.awt.Component;
import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

@SuppressWarnings("serial")
public class ToggleColor extends JPanel {

    public ToggleColor() {
        JButton button = new JButton(new MyButtonAction());
        button.setBackground(Color.GREEN);
        add(button);
    }

    private static void createAndShowGui() {
        ToggleColor mainPanel = new ToggleColor();

        JFrame frame = new JFrame("ToggleColor");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }
}

@SuppressWarnings("serial")
class MyButtonAction extends AbstractAction {
    // !! parallel arrays being used below -- avoid if possible
    private static final String[] TEXT = {"First", "Second", "Third"};
    private static final Color[] COLORS = {Color.GREEN, Color.RED, new Color(108, 160, 220)};
    private int index = 0;

    public MyButtonAction() {
        super(TEXT[0]);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        index++;
        index %= TEXT.length;
        putValue(NAME, TEXT[index]);
        Component c = (Component) e.getSource();
        c.setBackground(COLORS[index]);
    }
}

这使用了一个类似于 ActionListener 的 AbstractAction class,但是在 "steroids"