Java 在 JLabel 上添加和删除图标
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2235569/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 05:04:44 来源:igfitidea点击:
Add and remove an icon on a JLabel
提问by samuel
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?
嗨,我有一个标签,我为它设置了一个图标,我想在点击一个按钮后删除这个图标,它的方法是什么?
回答by ndeuma
label.setIcon(null)
in the event handler that handles the button click, if you're using Swing.
如果您使用的是 Swing,则在处理按钮单击的事件处理程序中。
回答by Adamski
// 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();
}
});