gpt4 book ai didi

java - 如何在JRadioButton 上设置图片和文字?

转载 作者:行者123 更新时间:2023-11-29 03:22:24 25 4
gpt4 key购买 nike

我在我的应用程序中使用 Swing 和 JRadioButton。我需要在我的按钮上设置图像和文本。为此,我正在使用这个:

JRadioButton button1 = new JRadioButton("text", iconpath, false);

但它给出的输出是隐藏单选按钮,只显示图像。

如何解决这个问题,有什么建议吗?我们也可以为 JCheckbox 创建类似的问题吗?

最佳答案

设置 JRadioButtonJCheckBox 的图标会替换这些控件使用的默认字形 - 我知道,这很烦人。

最简单的解决方案是简单地创建一个可以与JRadioButton 关联的JLabel,也许使用某种Map 来维护之间的联系

一个更长期的解决方案,可能是创建一个自定义组件,将概念结合到一个自定义和可重用的组件中,例如......

public class XRadioButton extends JPanel {

private JRadioButton radioButton;
private JLabel label;

public XRadioButton() {
setLayout(new GridBagLayout());
add(getRadioButton());
add(getLabel());
}

public XRadioButton(Icon icon, String text) {
this();
setIcon(icon);
setText(text);
}

protected JRadioButton getRadioButton() {
if (radioButton == null) {
radioButton = new JRadioButton();
}
return radioButton;
}

protected JLabel getLabel() {
if (label == null) {
label = new JLabel();
label.setLabelFor(getRadioButton());
}
return label;
}

public void addActionListener(ActionListener listener) {
getRadioButton().addActionListener(listener);
}

public void removeActionListener(ActionListener listener) {
getRadioButton().removeActionListener(listener);
}

public void setText(String text) {
getLabel().setText(text);
}

public String getText() {
return getLabel().getText();
}

public void setIcon(Icon icon) {
getLabel().setIcon(icon);
}

public Icon getIcon() {
return getLabel().getIcon();
}

}

关于java - 如何在JRadioButton 上设置图片和文字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22830489/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com