如何为JLabel创建事件处理程序? [英] How do I create an event handler for a JLabel?

查看:120
本文介绍了如何为JLabel创建事件处理程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想这样做,如果我点击JLabel,标签就会变成一个新标签,上面附有另一张图片。

I want to make it so that if I click on the JLabel, the label becomes a new label with another image attached to it.

到目前为止,我的代码看起来很像喜欢:

So far my code looks like:

public class Picture extends JFrame  {

    private ImageIcon _image1;
    private ImageIcon _image2;
    private JLabel _mainLabel;
    private JLabel _mainLabel2;

    public Picture(){
        _image1 = new ImageIcon("src/classes/picture1.jpg");
        _image2 = new ImageIcon("src/classes/picture2.jpg");
        _mainLabel = new JLabel(_image1);
        _mainLabel2 = new JLabel(_image2);

        add(_mainLabel);

        pack();
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}


推荐答案

添加mouseListener到你的JLable和 mouseClicked(mouseEvent) JLabel的方法更改图标。

Add mouseListener to your JLable and in mouseClicked(mouseEvent) method change icon of JLabel.

示例代码可能是:

  jLabel.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            jLabel.setIcon(newIcon);
        }
    });

这篇关于如何为JLabel创建事件处理程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆