简体   繁体   English

我可以在 JAVA 中使用多个 JButton 更改唯一的 MouseListener 方法吗?

[英]Can I change an unique MouseListener methods with several JButton in JAVA?

Goal目标

What I want to do is to set a MouseListener on a Panel when click on a Button1.我想要做的是在单击 Button1 时在面板上设置一个 MouseListener。 Then I want to click on another Button that changes the MouseListener code to do something else.然后我想单击另一个 Button 来更改 MouseListener 代码以执行其他操作。

Example of application应用示例

  1. Click on JButton1 -> add MouseListener that change a JLabel background color to red.单击 JButton1 -> 添加将 JLabel 背景颜色更改为红色的 MouseListener。
  2. Click on JButton2 -> DOESNT ADD a new MouseListener, but change the first one to set the JLabel text to "hello world"单击 JButton2 -> DOESNT ADD a new MouseListener,但更改第一个以将 JLabel 文本设置为“hello world”

What I can't do我不能做的事

I don't know how to modify an UNIQUE MouseListener.我不知道如何修改 UNIQUE MouseListener。

What I tried我试过的

I tried to set an jButton.actionPerformed( new jLabel1.addMouseListener()) for each button, but they create two instance of MouseListener.我试图为每个按钮设置一个 jButton.actionPerformed(new jLabel1.addMouseListener()),但它们创建了两个 MouseListener 实例。

I don't want to set one MouseListener for several JButtons, but several JButton changing the status of my MouseListener.我不想为多个 JButton 设置一个 MouseListener,而是多个 JButton 会更改我的 MouseListener 的状态。

Thanks alot :)非常感谢 :)

Better to give the JLabel a MouseListener from the get-go, but give it boolean if-blocks that will turn on or off functionality depending on the state of class boolean fields.最好从一开始就给 JLabel 一个 MouseListener,但给它布尔 if-blocks,它会根据类布尔字段的状态打开或关闭功能。 In your button ActionListeners, simply change the state of these boolean fields.在您的按钮 ActionListeners 中,只需更改这些布尔字段的状态。 For example in the code below, the boolean flag labelListenerOn is toggled on or off in the first JButton's ActionListener.例如,在下面的代码中,布尔标志labelListenerOn在第一个 JButton 的 ActionListener 中打开或关闭。 The JLabel's MouseListener checks the state of this variable and changes the labels background color if the flag is true only. JLabel 的 MouseListener 检查此变量的状态,并仅在标志为 true 时更改标签背景颜色。 Similarly for the other boolean flag and other ActionListener:对于其他布尔标志和其他 ActionListener 类似:

import java.awt.Color;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.*;

public class ButtonListener extends JPanel {
    private static final String TURN_ON_MOUSE = "Turn On Mouse";
    private static final String TURN_OFF_MOUSE = "Turn Off Mouse";
    private JButton button1 = new JButton(TURN_ON_MOUSE);
    private JButton button2 = new JButton("Button 2");
    private JLabel label1 = new JLabel("Label 1");
    private MouseListener labelListener = new LabelListener();
    private boolean labelListenerOn = false;
    private boolean labelChangeText = false;

    public ButtonListener() {
        label1.setOpaque(true);
        label1.addMouseListener(labelListener);

        button1.addActionListener(e -> {
            if (labelListenerOn) {
                labelListenerOn = false;
                ((JButton) e.getSource()).setText(TURN_ON_MOUSE);
            } else {
                labelListenerOn = true;
                ((JButton) e.getSource()).setText(TURN_OFF_MOUSE);
            }

        });
        
        button2.addActionListener(e -> {
            labelChangeText = true;
        });

        add(button1);
        add(button2);
        add(label1);
    }

    private class LabelListener extends MouseAdapter {
        @Override
        public void mousePressed(MouseEvent e) {
            Color labelColor = label1.getBackground();
            if (labelListenerOn) {
                if (labelColor.equals(Color.RED)) {
                    label1.setBackground(null);
                } else {
                    label1.setBackground(Color.RED);
                }
                // label1.repaint(); // per Rob Camick's comment, this is not necessary
            }
            
            if (labelChangeText) {
                label1.setText("Hello World");
            }
        }
    }

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

    private static void createAndShowGui() {
        ButtonListener mainPanel = new ButtonListener();
        JFrame frame = new JFrame("ButtonListener");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.add(mainPanel);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }
}

If you want to get fancy, look up MVC for "model-view-controller", where you separate the program logic (here the state of the boolean flags) from the program view code (the Swing GUI code), usually in their own classes, and then use a master class to hook all the components up.如果你想变得有趣,请查找 MVC 的“模型-视图-控制器”,在那里你将程序逻辑(这里是布尔标志的状态)与程序视图代码(Swing GUI 代码)分开,通常在它们自己的类,然后使用主类将所有组件连接起来。 This would add an additional layer of indirection and complexity, and would be over-kill in this situation, but in large programs, and especially in programs that are likely going to be updated, changed and grown, this will actually reduce complexity in the long run, and make the program much more "scalable" -- easier to grow and modify.这会增加一个额外的间接层和复杂性,在这种情况下会被过度杀伤,但是在大型程序中,尤其是在可能会更新、更改和增长的程序中,这实际上会长期降低复杂性运行,并使程序更具“可扩展性”——更易于增长和修改。 Again, I do not recommend that you do this here, but do look it over for possible future use.同样,我不建议您在此处执行此操作,但请仔细查看以备将来使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM