gpt4 book ai didi

java - doClick() 和西蒙 : All buttons will unpress at the same time instead of individually

转载 作者:行者123 更新时间:2023-11-29 05:12:47 25 4
gpt4 key购买 nike

您好,我是 stackoverflow 的新手,如果我犯了错误,请多多包涵。

我正在为一个类(class)项目制作这个Java Simon Says Game。它由每个序列号的随机数生成器工作。我通过 doClick() 显示序列,但事先删除了 actionlisteners,然后再添加它。

问题是在按下所有其他按钮之前,按钮不会松开或解除武装。我试过使用 thread.sleep 在每个 if...else 语句之间放置一个延迟,但它只会被按下更长时间。我尝试在 thread.sleep 的 try...catch 中通过 repaint()、revalidate()、updateUI() 更新 gui,但这也不起作用。

我意识到这个问题主要是表面问题,因为当我尝试实现 setPressed 或 setArmed 时,它说它没有被按下,但它看起来是被按下的。

这是最简单形式的代码片段,没有 thread.sleep 或我之前在评论中的尝试。

public void sequence2() //This is where the issue happens. The buttons won't unpress until every button has been pressed.

{
level.setText(" Level 2"); //Level indicator

Green.removeActionListener(Listener);
Red.removeActionListener(Listener);
Yellow.removeActionListener(Listener);
Blue.removeActionListener(Listener);

if(sequence1 == 1)
{
Green.doClick(300); //Programmatically clicks the button
}
else if(sequence1 == 2)
{
Red.doClick(300);
}
else if(sequence1 == 3)
{
Yellow.doClick(300);
}
else if(sequence1 == 4)
{
Blue.doClick(300);
}

if(sequence2 == 1)
{
Green.doClick(300);
}
else if(sequence2 == 2)
{
Red.doClick(300);
}
else if(sequence2 == 3)
{
Yellow.doClick(300);
}
else if(sequence2 == 4)
{
Blue.doClick(300);
}

Green.addActionListener(Listener);
Red.addActionListener(Listener);
Yellow.addActionListener(Listener);
Blue.addActionListener(Listener);

}

我是 java 的新手,所以我不擅长多线程处理或以这种方式处理事件调度线程。但如果这是唯一的解决方案,我将需要更多帮助。

我在一个 zip 文件中有完整的代码,如果有帮助的话,之前的尝试被注释掉了。 https://drive.google.com/file/d/0Bxg4WleC9jD2VFhoZmZBNjV6Vkk/view?usp=sharing

最佳答案

为此调用 doClick() 可能是一个尴尬的选择,因为它使用了 Timer在内部。相反,使用 JToggleButton ,这将允许您使用 setSelected() 根据按钮的 selected 状态控制每个按钮的外观。游戏中显示了一个完整的示例 Buttons .在您的 Swing 的 ActionListenerTimer , 选择当前按钮, play它的注释并增加 sequence 索引。播放完所有音符后,取消选择所有按钮。

附录:你能展示一下你是如何实现计时器的吗?

概括地说,给定一个合适的切换按钮列表:

private static final int MAX = 4;
List<JToggleButton> buttons = new ArrayList<JToggleButton>(MAX);
private int i;

定时器的监听器可能看起来像这样:

@Override
public void actionPerformed(ActionEvent e) {
Object src = e.getSource();
JToggleButton b = buttons.get(i);
if (i > MAX) { // reset i and all the buttons
for (JToggleButton b : buttons) {
b.setSelected(false);
}
timer.stop();
i = 0;
} else {
b.setSelected(true);
// play tone i
i++;
}
}

切换按钮的项目监听器应根据其状态指示更新按钮的外观:

@Override
public void itemStateChanged(ItemEvent e) {
JToggleButton b = (JToggleButton) e.getItem();
if (b.isSelected()) {
// change icon, color etc.
} else {
// restore icon, color etc.
}
}

关于java - doClick() 和西蒙 : All buttons will unpress at the same time instead of individually,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27760416/

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