1
I have a Jlabel that receives an event, and would like to disable that event when the component is disabled (setEnable = false), and only activate it again when the component is enabled.
what I did:
import java.awt.Cursor;
import java.awt.event.ItemEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.ImageIcon;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class NovoClass extends JFrame {
private JPanel painel = new JPanel();
public NovoClass() {
setSize(200, 150);
ImageIcon image = new ImageIcon(getClass().getResource("/imagens/botãoExcluir.png"));
JLabel imagelabel = new JLabel(image);
JCheckBox check = new JCheckBox("Enable/Disable");
imagelabel.addMouseListener(getMouseListener());
imagelabel.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
painel.add(imagelabel);
imagelabel.setEnabled(false);
add(painel);
painel.add(check);
check.addItemListener((ItemEvent e) -> {
if (check.isSelected() == true) {
imagelabel.setEnabled(true);
imagelabel.addMouseListener(getMouseListener());
} else {
imagelabel.setEnabled(false);
//retirar evento.
}
});
setVisible(true);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public MouseListener getMouseListener() {
return new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
JOptionPane.showMessageDialog(null, "Clicou aqui !");
}
};
}
public static void main(String[] args) {
NovoClass novo = new NovoClass();
}
}
What is the purpose of removing a system from a disabled component?
– user28595
@Article here I did not want to extend much the code, more the component in some situations, opens Jdialogs, when disabled, I want to prevent the user to be able to click on the label, and open them.
– JavaTech
It still doesn’t make sense. I think you’re visualizing it from the wrong side. Instead of removing and resetting event in component, why not check if component is disabled before event action?
– user28595
@Once again that it is enabled, and win the event, if it is disabled later, the event will remain there, it will not ask it, so even if disabled, if it is clicked it will "run".
– JavaTech
See the suggestion of my last comment. The approach suggested in it solves this. In your Mouselistener, check if the clicked component is active, if yes, do the action, if not, do nothing.
– user28595
@Articuno I tried here, but it didn’t work, the only difference was the first time, as it gets disabled, then it worked the condition. However, after it is enabled 1 time, the event "continues there"
– JavaTech
How are you doing?
– user28595
using isEnable I see if the imageLabel ta habiltado, if it has it calls the method of the event.
– JavaTech