【发布时间】:2022-01-14 16:30:09
【问题描述】:
我想在 JRadioButton 启用或禁用时更改它的文本。如果按钮被禁用,它应该显示一个文本,当它被禁用时,它应该显示另一个文本。不知何故,我设法让它在启用时更改文本。但我的问题是,即使按钮被禁用,它也会在启用时显示文本。我尝试使用 JCheckBox 而不是 JRadioButton 问题没有解决。这是代码;
'''
radiobtn() {
this.setSize(500, 300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.getContentPane().setBackground(new Color(0x00CCFFAAFF));
this.setTitle("Radio Button example");
this.setLayout(new FlowLayout(FlowLayout.CENTER, 20, 52));
loveIcon = new ImageIcon("radio_icon\\icon (1).png");
sadIcon = new ImageIcon("radio_icon\\icon (2).png");
angryIcon = new ImageIcon("radio_icon\\icon (4).png");
wowIcon = new ImageIcon("radio_icon\\icon (3).png");
hahaIcon = new ImageIcon("radio_icon\\icon (6).png");
careIcon = new ImageIcon("radio_icon\\icon (5).png");
love = new JRadioButton("Loved");
love.setBackground(null);
love.setFocusable(false);
love.setForeground(new Color(0x00000));
love.setFont(new Font("Comic Sans MS", Font.PLAIN, 20));
love.setIcon(loveIcon);
love.setSelectedIcon(wowIcon);
love.addItemListener(this);
sad = new JRadioButton("Sad");
sad.setBackground(null);
sad.setFocusable(false);
sad.setForeground(new Color(0x00000));
sad.setFont(new Font("Comic Sans MS", Font.PLAIN, 20));
sad.setIcon(sadIcon);
sad.setSelectedIcon(hahaIcon);
sad.addItemListener(this);
angry = new JRadioButton("Angry");
angry.setBackground(null);
angry.setFocusable(false);
angry.setForeground(new Color(0x00000));
angry.setFont(new Font("Comic Sans MS", Font.PLAIN, 20));
angry.setIcon(angryIcon);
angry.setSelectedIcon(careIcon);
angry.addItemListener(this);
this.add(love);
this.add(angry);
this.add(sad);
this.setVisible(true);
}
public static void main(String[] args) {
new radiobtn();
}
@Override
public void itemStateChanged(ItemEvent e) {
boolean ok = e.getStateChange()==ItemEvent.SELECTED;
System.out.println(ok);
if(ok=true)
love.setText("Wow");
}
}
'''
在上面的代码中,当按钮启用时,我想将爱按钮的文本从 Loved 更改为 Wow,当按钮禁用时,我想从 Wow 更改为 Loved。当我单击该按钮时,它确实将文本更改为哇,但是当我再次单击它以禁用它时,文本不会更改回它的原始文本,即 Loved。设置好哇。
【问题讨论】:
-
1) Edit 添加minimal reproducible example。它应该包含足够的代码以使其在屏幕上显示而无需更改(例如,添加
import语句和class结构),但删除任何不需要证明问题的内容(例如,所有图标、字体以及不超过 一个启用/禁用控制)。 2)radiobtn应该是RadioBtn以便正确使用类名的大小写。 3)this.setSize(500, 300);这只是一个猜测。对于正确的大小,添加所有组件然后调用this.pack();。 -
.. 4)
if(ok=true)应该是if(ok)5)love.setEnabled(false)在哪里调用? NVM 我会在 MRE 中寻找它,它有望在添加 3 个接近投票之前出现。 -
“启用”或“选择” - 这些是不同的概念
标签: java swing jradiobutton