簡體   English   中英

如何在JRadioButton標簽上添加actionlistener?

[英]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建議的那樣,您應該創建自己的組件,其中包含JRadioButtonJLabel

這是一個示例,為您提供了一種主要的測試方法以及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