Java 从JLabel创建的图像按钮不工作

Java 从JLabel创建的图像按钮不工作,java,Java,我正在尝试使用ImageIcon和addMouseListener从JFrame上的一个图像创建一个按钮,通过单击它将当前图像替换为另一个图像 static JPanel jp = new JPanel(); final JLabel jl = new JLabel(); final JFrame jf = new JFrame(); ImageIcon image = new ImageIcon("image1.jpg"); jl.setIcon(image); jp

我正在尝试使用ImageIcon和addMouseListener从JFrame上的一个图像创建一个按钮,通过单击它将当前图像替换为另一个图像

static JPanel jp = new JPanel();
final JLabel jl = new JLabel();
final JFrame jf = new JFrame();

    ImageIcon image = new ImageIcon("image1.jpg");
    jl.setIcon(image);
    jp.add(jl);
    jf.add(jp); 
    jf.validate();

    JLabel button = new JLabel(image);
    button.addMouseListener(new MouseAdapter() {
        public void mouseClicked(MouseEvent e) {
            jl.setIcon( null );
            ImageIcon image = new ImageIcon("image2.jpg");
            jl.setIcon(image);
        }
    });
GUI显示为image1.jpg,但按钮根本不起作用,我甚至无法测试从image1到image2的替换是否起作用。即使我尝试单击窗口上显示的image1.jpg,GUI也不会执行任何操作

编辑:将JLabel变量调整为最终版本。其他类似的问题表明这种方法应该有效,但我无法找出代码的错误

也不确定ActionListener是否能与JLabel一起工作

不,您不能将ActionListener添加到JLabel。更简单的方法是使JButton看起来像JLabel,然后可以将ActionListener添加到按钮:

JButton button = new JButton(...);
button.setBorderPainted(false);
button.setContentAreaFilled(false);
button.addActionListener(...);
但是按钮根本不起作用


当接收到同一鼠标点的mousePressed和MouseRelease时,将生成鼠标单击。因此,如果您稍微移动鼠标,则不会生成事件。而是监听mousePressed()事件。

您应该使用
ActionListener
作为按钮。我只是想让图像可以单击以命令操作。也不确定ActionListener是否能与JLabel一起工作。您的“button”变量是什么类类型?请说明它是如何声明和初始化的。您的标题表明它是一个JLabel,如果是这样的话,那么变量名就具有很强的误导性,因为它表明它实际上是一个JButton或类似的东西。考虑清楚你的问题。请不要给JLable对象名为“Butt”。同样,这是误导性的。看起来您在JLabel中添加了一个名为“button”的鼠标侦听器,我看不到它添加到面板中。您是否在单击名为“jl”的JLabel时认为它是“按钮”?