没有 javac 编译器错误,但 mouseEntered 方法不起作用

No javac compiler error but mouseEntered method is not working

我正在尝试制作一个程序,当您将鼠标悬停在一个元素上时,它会被设置为不可见,而新的元素将在不同的地方设置为可见。但是,当我将鼠标悬停在按钮上时,什么也没有发生。没有编译器错误告诉我要修复什么,所以我来到堆栈溢出。我在 Java 方面非常缺乏经验,我昨天才开始,所以如果你能帮我把它简化一下。这是我的代码:


import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class hover {

    public static void main(String args[]) {

        JFrame f = new JFrame("Java Swing UI");
        GridLayout l = new GridLayout(2,4);
        JButton b = new JButton("Click me!");
        JButton b2 = new JButton("Click me!");
        f.setSize(500,300);
        f.setLayout(l);
        b.setBackground(Color.WHITE);
        b2.setBackground(Color.WHITE);
        f.add(b);
        f.add(b2);
        b2.setVisible(false);

        b.addMouseListener(new MouseAdapter() {

            @Override
            public void mouseEntered(MouseEvent e) { 

                if (e.getSource() == f) {
                    b.setVisible(false);
                    b2.setVisible(true);
                }


            }

        });
        f.setVisible(true);
    }
}

I am very inexperienced in Java and I just started yesterday

因此,您需要学习的第一件事是如何使用 System.out.println(…) 进行一些基本调试,以查看您的逻辑是否按照您的预期进行。例如:

@Override
public void mouseEntered(MouseEvent e) { 
    System.out.println("mouse entered");
    if (e.getSource() == f) {
        System.out.println("if statement");
        b.setVisible(false);
        b2.setVisible(true);
    }
}

如果你这样做了,你会注意到当你 运行 你的代码时,你不会看到 "if statement" 显示。所以问题是为什么?

b.addMouseListener(new MouseAdapter() {

您已将 MouseListener 添加到 "b" 变量。

if (e.getSource() == f) {

但是您的 if 语句检查事件是否来自 "f" 变量,这永远不会是真的。

不需要 if 语句,因为只能为 "b" 按钮生成事件。因此你只需要:

@Override
public void mouseEntered(MouseEvent e) 
{ 
        b.setVisible(false);
        b2.setVisible(true);
}