我能否在JAVA中使用多个JButton更改唯一的MouseListener方法?

huangapple go评论67阅读模式
英文:

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

问题

目标

我想要做的是,在点击Button1时,在Panel上设置一个MouseListener。然后我想要点击另一个Button,将MouseListener代码更改为执行其他操作。

应用示例

  1. 点击JButton1 -> 添加MouseListener,将JLabel的背景颜色更改为红色。
  2. 点击JButton2 -> 不会添加新的MouseListener,而是将第一个MouseListener更改为将JLabel的文本更改为“hello world”。

我不能做到的

我不知道如何修改唯一的MouseListener。

我尝试过的

我尝试为每个按钮设置jButton.actionPerformed( new jLabel1.addMouseListener()),但它们会创建两个MouseListener的实例。

我不想为几个JButton设置一个MouseListener,而是希望有几个JButton可以更改我的MouseListener的状态。

非常感谢 我能否在JAVA中使用多个JButton更改唯一的MouseListener方法?

英文:

Goal

What I want to do is to set a MouseListener on a Panel when click on a Button1.
Then I want to click on another Button that changes the MouseListener code to do something else.

Example of application

  1. Click on JButton1 -> add MouseListener that change a JLabel background color to red.
  2. Click on JButton2 -> DOESNT ADD a new MouseListener, but change the first one to set the JLabel text to "hello world"

What I can't do

I don't know how to modify an 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.

I don't want to set one MouseListener for several JButtons, but several JButton changing the status of my MouseListener.

Thanks alot 我能否在JAVA中使用多个JButton更改唯一的MouseListener方法?

答案1

得分: 3

最好从一开始就为JLabel添加一个MouseListener,但为其设置布尔类型的if条件块,这些条件块将根据类布尔字段的状态来开启或关闭功能。在按钮的ActionListener中,只需改变这些布尔字段的状态。例如在下面的代码中,布尔标志labelListenerOn在第一个JButton的ActionListener中被切换开或关。JLabel的MouseListener检查此变量的状态,并仅在标志为true时更改标签的背景颜色。其他布尔标志和其他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);
                }
            }

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

如果你想变得更加高级,可以查找"model-view-controller"中的M-V-C,其中将程序逻辑(即布尔标志的状态)与程序视图代码(Swing GUI代码)分离,通常放在各自的类中,然后使用主类将所有组件连接起来。这会增加一个额外的间接和复杂性层,虽然在这种情况下可能有些过度,但在大型程序中,特别是在可能会被更新、改变和扩展的程序中,这实际上会降低复杂性,使程序在长期内更加"可扩展"——更易于增长和修改。再次强调,我不建议在这里使用,但可以在可能的将来考虑一下。

英文:

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. In your button ActionListeners, simply change the state of these boolean fields. For example in the code below, the boolean flag labelListenerOn is toggled on or off in the first JButton's ActionListener. The JLabel's MouseListener checks the state of this variable and changes the labels background color if the flag is true only. Similarly for the other boolean flag and other 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 M-V-C 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. 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.

huangapple
  • 本文由 发表于 2020年8月30日 00:21:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/63649240.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定