J Label and J checkbox

420 views Asked by At

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);
2

There are 2 answers

0
user3437460 On

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                    
    }
});
1
AudioBubble On

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();
   }
});