By looping, I created tags. I need to, when I click on them with the mouse, they disappear. She clicked on one, she disappeared, on the other and so on. But when I launch, the labels do not disappear. What needs to be done to make everything work as it should?

lol = new JPanel(); lol.setBounds(10, 47, 974, 693); contentPane.add(lol); lol.setLayout(null); for (int k = 0; k < 50; k++){ label_2 = new JLabel(""); label_2.setIcon(new ImageIcon(P.class.getResource("/images/00.png"))); int w = randomRange(10, 974); int r = randomRange(10, 693); label_2.setBounds(w, r, 200, 200); label_2.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { lol.remove(label_2); } }); lol.add(label_2); } 
  • one
    I will order a seal for myself: "The code does not work as it should. Polykhaev." Somewhere in MouseEvent should be a link to the clicked control. Here it should be removed. - Igor
  • try to reduce the number of tags, for example, to 3, and see if no label really disappears - Grundy
  • 2
    Most likely, the last label is still deleted .. - vp_arth
  • link to clicked control? - cerulean
  • reduced, but still does not work ... - cerulean

3 answers 3

 lol.remove((JLabel)e.getComponent()); 

or

 lol.remove((JLabel)e.getSource()); 
  • where to insert it? I'm sorry, I don't understand well. - cerulean
  • four
    "Hussars to be silent!" - Instead of your line lol.remove(label_2); - Igor
  • pasted, but did not help ... - cerulean
  • one
    and, excuse me, no, it helped, somehow we had to click, but they disappear! thank! - cerulean

And the option with the cycle to complete the picture:

 for (int k = 0; k < 50; k++) { JLabel label_2 = new JLabel("Label" + k); label_2.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { lol.remove(label_2); } }); lol.add(label_2); } 

The difference is that the variable label_2 declared inside the loop, not outside. Therefore, in the inner class the label from the current iteration is used, and not the last created one.

After lol.remove(label_2); frame.repaint(); can be added to the event handler frame.repaint(); , if there is no constant drawing in the loop.

  • thank you very much! works! - cerulean

The problem is closure, namely in this line:

 lol.remove(label_2); 

When the loop finishes, the last label set is in the label_2 variable. When it executes a click event, only this last tag is deleted. You need to change the method of deletion (or rather, the method of obtaining the desired label instance)

  • That is, you need to somehow change the way you create tags? or removal method. - cerulean