【问题标题】:How to add actionlistener to JRadioButton label?如何将 actionlistener 添加到 JRadioButton 标签?
【发布时间】:2015-12-11 22:38:26
【问题描述】:

我想创建一个具有两个侦听器的 radioButton,一个在单选按钮上,另一个在标签上。第一个应该为他的选择状态做正常的单选按钮工作,第二个应该做我的自定义操作。 我的组件的问题是在按钮上绘制标签,见下图。 任何帮助或更好的想法将不胜感激。

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

【问题讨论】:

  • 您正在将 JLabel 添加到 JRadioButton,您期望什么?
  • 不要扩展 JRadioButton!!改用合成!有一个 RadioLabelButton,它是一个包含单选按钮和标签的面板。
  • 您选择不使用其setText method 设置JRadioButton 的文本是否有原因?
  • 这是因为JRadioButton在API中没有合理实现LayoutManager
  • 原因是我想用单选按钮创建一个望远镜菜单。欢迎任何新想法。

标签: java swing jbutton jlabel jradiobutton


【解决方案1】:

按照 Oliver Watkins 的建议,您应该创建自己的组件,其中包含 JRadioButtonJLabel

这是一个示例,它为您提供了一个 main 方法进行测试,以及 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;
    }

}

【讨论】:

    猜你喜欢
    • 2016-12-15
    • 2012-06-30
    • 1970-01-01
    • 2021-06-24
    • 1970-01-01
    • 1970-01-01
    • 2012-06-25
    • 2013-04-01
    • 1970-01-01
    相关资源
    最近更新 更多