简体   繁体   English

如何在JRadioButton标签上添加actionlistener?

[英]How to add actionlistener to JRadioButton label?

I would like to create a radioButton which have two listener, one on the radio button and the other one on the label. 我想创建一个单选按钮,它有两个侦听器,一个在单选按钮上,另一个在标签上。 first one should do as normal radio button jobs for his selection state and the second one should do my custom action. 第一个应该在其选择状态下执行正常的单选按钮工作,第二个应该执行我的自定义操作。 Problem with my component is that paint the label on the button see attached picture below. 我的组件的问题是在按钮上涂了标签,请参见下面的图片。 Any help or better idea will be appreciated. 任何帮助或更好的主意将不胜感激。

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

在此处输入图片说明

As Oliver Watkins suggested, you should create your own component containing a JRadioButton , and a JLabel . 正如Oliver Watkins建议的那样,您应该创建自己的组件,其中包含JRadioButtonJLabel

Here is an example, that provides you with a main method for testing, and getter methods to retrieve the label and the button, so that you can do things with them, like adding action listeners. 这是一个示例,为您提供了一种主要的测试方法以及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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM