[英]J Label and J checkbox
I have a Jlabel and a checkbox. 我有一个Jlabel和一个复选框。 I want to make it so that I can click on the Jlabel and the checkbox will be ticked.
我要这样做,以便可以单击Jlabel,然后将复选框打勾。 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 在Java 8之前,您可以
_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. 您可以考虑将
MouseListener
添加到JLabel并重写mouseClicked()
方法。
_mylabel.addMouseListener(new MouseAdapter(){
@Override
public void mouseClicked(MouseEvent e){
//do whatever
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.