I have a Jlabel and a checkbox. I want to make it so that I can click on the Jlabel and the checkbox will be ticked. I need it to be a label because I use it for something else. Normally what I do is to just have a checkbox only with some text, but this time I need a label and checkbox, and I need the label to tick the checkbox when clicked upon. Below is the code I have. I have tried to add an action listener to the label but i get an error saying its an undefined type. Thank you...
JCheckBox _mycheckbox = new JCheckBox();
JLabel _mylabel = new JLabel(_mylabel);
Simple way is having text assigned to checkbox itself:
JCheckBox _mycheckbox = new JCheckBox("Tick Me"); //gives you checkbox, along with clickable text
Other option is having action listener on label to simulate click on checkbox:
_mylabel.addActionListener((e)->_mycheckbox.doClick()); //java 8 lambda
Prior to Java 8, you can do
_mylabel.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent ae){
_mycheckbox.doClick();
}
});
You can consider adding a MouseListener
to your JLabel and override the mouseClicked()
method.
_mylabel.addMouseListener(new MouseAdapter(){
@Override
public void mouseClicked(MouseEvent e){
//do whatever
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.