i want to remove imageicon according to clicking on button

583 Views Asked by At

I want to set the icon on a label when button pressed once if pressed twice it will remove i have used label.setIcon(null); but it is not working fine for me.

public void actionPerformed(ActionEvent e) {
    if (!"submit".equals(e.getActionCommand()))
    {
       JButton button = (JButton) e.getSource();
       int X = button.getLocation().x;  
       int Y = button.getLocation().y;
       JLabel tick=new JLabel();add(tick);
       tick.setBounds(X+400,Y+15,50,50);           

       if(arr.contains(e.getActionCommand()))
       {            
           tick.setIcon(null);
           arr.remove(e.getActionCommand());
       }          
       else
       {            
           image=new ImageIcon(imageList[0]);
           tick.setIcon(image);
           arr.add(e.getActionCommand());
       }
1

There are 1 best solutions below

7
On BEST ANSWER

Don't recreate JLabel and don't add it on each click

   JLabel tick=new JLabel();
   add(tick);

Create class' field instead and create the label once. If it's initialized just tick.setIcon(null).