目标
我想要做的是当单击 Button1 时在面板上设置 MouseListener。 然后我想单击另一个按钮来更改 MouseListener 代码以执行其他操作。
应用示例
- 单击 JButton1 -> 添加 MouseListener,将 JLabel 背景颜色更改为红色。
- 单击 JButton2 -> 不添加新的 MouseListener,但更改第一个以将 JLabel 文本设置为“hello world”
我不能做什么
我不知道如何修改 UNIQUE MouseListener。
我尝试了什么
我尝试为每个按钮设置一个 jButton.actionPerformed( new jLabel1.addMouseListener()) ,但它们创建了两个 MouseListener 实例。
我不想为多个 JButton 设置一个 MouseListener,但多个 JButton 会更改我的 MouseListener 的状态。
非常感谢:)
最佳答案
最好从一开始就为 JLabel 提供一个 MouseListener,但为其提供 boolean if block ,该 block 将根据类 boolean 字段的状态打开或关闭功能。在按钮 ActionListener 中,只需更改这些 boolean 字段的状态即可。例如,在下面的代码中, boolean 标志 labelListenerOn
在第一个 JButton 的 ActionListener 中打开或关闭。 JLabel 的 MouseListener 检查此变量的状态,并仅在标志为 true 时更改标签背景颜色。对于其他 boolean 标志和其他 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);
}
}
如果你想变得更奇特,可以在 M-V-C 中查找“模型- View - Controller ”,在这里你可以将程序逻辑(这里是 boolean 标志的状态)与程序 View 代码(Swing GUI 代码)分开,通常在他们自己的类中,然后使用主类来连接所有组件。这将增加额外的间接层和复杂性,并且在这种情况下会过度杀伤,但在大型程序中,特别是在可能要更新、更改和增长的程序中,这实际上会减少/em> 从长远来看,复杂性,并使程序更加“可扩展”——更容易增长和修改。再次强调,我不建议您在此处执行此操作,但请仔细检查以供将来使用。
关于java - 我可以用JAVA中的几个JButton来改变一个独特的MouseListener方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63649240/