gpt4 book ai didi

java - Button.isSelected() 不返回 true

转载 作者:行者123 更新时间:2023-12-02 08:52:47 25 4
gpt4 key购买 nike

我正在创建一个带有 3 个按钮、3 个复选框和 3 个单选按钮的 JFrame。我遇到按下 3 个按钮中的 1 个按钮时执行的功能的问题。这是函数:

private void setCenterColors() {

if(redB.isSelected()) {
center.setBackground(Color.RED);
} else if (greenB.isSelected()) {
center.setBackground(Color.GREEN);
} else if (blueB.isSelected()){
center.setBackground(Color.BLUE);
}
System.out.println(center.getBackground());
}

redB、greenB 和 blueB 都是 JButton。

按钮的事件处理程序是:

class ChoiceListenerButton implements ActionListener {
public void actionPerformed(ActionEvent event)
{
setCenterColors();
repaint();
}
}

listenerButton = new ChoiceListenerButton();

当我执行程序并按下按钮时,所有按钮都返回 false,而其中一个应该返回 true。我应该怎么做才能看到按下了哪个按钮?感谢任何帮助,如果您需要完整的代码,请询问,我会在看到通知后立即重播。谢谢。

最佳答案

按如下方式进行:

class ChoiceListenerButton implements ActionListener {
public void actionPerformed(ActionEvent event) {
setCenterColors(event);
repaint();
}

private void setCenterColors(ActionEvent event) {
if(event.getSource() == redB) {
center.setBackground(Color.RED);
} else if (event.getSource() == greenB) {
center.setBackground(Color.GREEN);
} else if (event.getSource() == blueB){
center.setBackground(Color.BLUE);
}
System.out.println(center.getBackground());
}
}

此外,请确保您已将 listenerButton 添加到按钮,例如redB.addActionListener(listenerButton).

关于java - Button.isSelected() 不返回 true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60676254/

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