Add and remove icon on JLabel

Hi, I have a label that I set an icon for her, I want to delete this icon after clicking on the button, what method is for it?

+5
source share
2 answers
// 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();
  }
});
+12
source
label.setIcon(null) 

in an event handler that handles button clicks if you use Swing.

+6
source

All Articles