简体   繁体   中英

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 .

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.

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

}

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.

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