2015-12-11 130 views
0

我想創建一個radioButton,它有兩個監聽器,一個在單選按鈕上,另一個在標籤上。第一個應該爲他的選擇狀態做正常的單選按鈕作業,第二個應該做我的自定義操作。 我的組件存在的問題是在按鈕上繪製標籤,請參閱下面的附加圖片。 任何幫助或更好的主意將不勝感激。如何將actionlistener添加到JRadioButton標籤?

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

enter image description here

+4

您正在爲JRadioButton添加JLabel,您期待什麼? – Berger

+5

不要擴展JRadioButton!改用組合物吧!有一個RadioLabelButton,它是一個包含單選按鈕和標籤的面板。 –

+2

是否有原因,您選擇不使用[setText方法]設置JRadioButton的文本(http://docs.oracle.com/javase/8/docs/api/javax/swing/AbstractButton.html#setText-java。 lang.String-)? – VGR

回答

3

由於奧利弗·沃特金斯建議,你應該創建一個包含JRadioButtonJLabel自己的組件。

下面是一個例子,爲您提供用於測試的方法,並吸氣方法來檢索標籤和按鈕,這樣就可以做的事情與他們一樣,添加動作監聽器。

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

}