2015-12-11 129 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; 
    } 

}