[英]How to add actionlistener to JRadioButton label?
我想创建一个单选按钮,它有两个侦听器,一个在单选按钮上,另一个在标签上。 第一个应该在其选择状态下执行正常的单选按钮工作,第二个应该执行我的自定义操作。 我的组件的问题是在按钮上涂了标签,请参见下面的图片。 任何帮助或更好的主意将不胜感激。
private class RadioLabelButton extends JRadioButton{
private JLabel label;
protected boolean lblStatus;
private RadioLabelButton(JLabel label,Font font,Color color) {
lblStatus = false;
this.label = label;
label.setFont(font);
label.setForeground(color);
add(label, BorderLayout.WEST);
}
}
正如Oliver Watkins建议的那样,您应该创建自己的组件,其中包含JRadioButton
和JLabel
。
这是一个示例,为您提供了一种主要的测试方法以及getter方法来检索标签和按钮,以便您可以对它们进行操作,例如添加动作侦听器。
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
public class JRadioLabelButton extends JPanel {
private final JRadioButton radioButton;
private final JLabel label;
public JRadioLabelButton(final String text) {
radioButton = new JRadioButton();
label = new JLabel(text);
add(radioButton);
add(label);
}
public static void main(final String[] args) {
JFrame fr = new JFrame();
JRadioLabelButton myRadioLabelButton = new JRadioLabelButton("some text");
JLabel label = myRadioLabelButton.getLabel();
// do things with the label
JRadioButton radioButton = myRadioLabelButton.getRadioButton();
// do things with the radio button
fr.getContentPane().add(myRadioLabelButton);
fr.pack();
fr.setVisible(true);
}
public JRadioButton getRadioButton() {
return radioButton;
}
public JLabel getLabel() {
return label;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.