Add and remove an icon on a JLabel

后端 未结 2 1537
夕颜
夕颜 2021-01-12 13:17

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?

相关标签:
2条回答
  • 2021-01-12 13:38
    // 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();
      }
    });
    
    0 讨论(0)
  • 2021-01-12 13:56
    label.setIcon(null) 
    

    in the event handler that handles the button click, if you're using Swing.

    0 讨论(0)
提交回复
热议问题