如何将 actionlistener 添加到 JRadioButton 标签?
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 所建议的那样,您应该创建自己的组件,其中包含一个 JRadioButton
和一个 JLabel
.
这里有一个例子,它提供了一个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;
}
}
我想创建一个有两个侦听器的单选按钮,一个在单选按钮上,另一个在标签上。第一个应该为他的选择状态做正常的单选按钮工作,第二个应该做我的自定义操作。 我的组件的问题是在按钮上绘制标签,请参见下面的附图。 任何帮助或更好的想法将不胜感激。
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 所建议的那样,您应该创建自己的组件,其中包含一个 JRadioButton
和一个 JLabel
.
这里有一个例子,它提供了一个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;
}
}