在JLabel上添加和删除图标 [英] Add and remove an icon on a JLabel

查看:134
本文介绍了在JLabel上添加和删除图标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨我有一个标签,我为它设置了一个图标,我想在点击一个按钮后删除这个图标,它的方法是什么?

hi i have a label that i have set a icon for it, i want to remove this icon after clicking on a button, what is the method for it?

推荐答案

// Create icon
Icon icon = new ImageIcon(getClass().getResource("/foo/bar/baz.png"));

// Create label
final JLabel lbl = new JLabel("Hello, World", icon, JLabel.LEFT_ALIGNMENT);

// Create button
JButton btn = new JButton("Click Me");
btn.addActionListener(new ActionListener() {
  public void actionPerformed(ActionEvent evt) {
    // Remove icon when button is clicked.
    lbl.setIcon(null);

    // **IMPORTANT** to call revalidate() to cause JLabel to resize and be repainted.
    lbl.revalidate();
  }
});

这篇关于在JLabel上添加和删除图标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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