有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

从JLabel创建的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.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,GUI也不会做任何事情。窗口上显示了jpg

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


共 (1) 个答案

  1. # 1 楼答案

    Not really sure ActionListener works with JLabel either.

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

    JButton button = new JButton(...);
    button.setBorderPainted(false);
    button.setContentAreaFilled(false);
    button.addActionListener(...);
    

    but the button does not work at all

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