在 Java Swing 中等待多个按钮输入 [英] Waiting for multiple button inputs in Java Swing
问题描述
对不起,我的英语不好,不是母语人士.我正在 GUI 中开发基于 Java 的 SimonSays 游戏.我是编码新手.我设法使应用程序在控制台上工作,但是使其以图形方式工作是一团糟.该程序将生成的序列 (secuenciaSimon) 中的 LinkedLists 与用户通过按钮输入的序列 (secuenciaUsuarioGUI) 进行比较,但是,问题是比较方法是通过单击任何按钮调用的,因此 simon 生成的序列中的 LinkedList比用户介绍的大.
Sorry from my bad english, not native speaker. I am working on a SimonSays Game on Java in a GUI. Im new to coding. I managed to make the aplication work on console, however its been a mess to make it work graphically. The program compares the LinkedLists from the generated sequence (secuenciaSimon) to the one entered by the user throught buttons (secuenciaUsuarioGUI) however, the problem is that the compare method is called by a click on any button so the LinkedList from the generated Sequence by simon is larger that the one introduced by the user.
黄色按钮代码
private void bAmarilloMousePressed(java.awt.event.MouseEvent evt) {
secuenciaUsuarioGUI.add(3); //Adds the selection to the LinkedList yellow=3
System.out.println("Secuencua Usuario GUI:" + secuenciaUsuarioGUI.toString());
comparaSecuencia();
generaSecuencia(); //Adds another value to the LinkedList
}
比较代码
public boolean comparaSecuencia(){
for (int i = 0; i < secuenciaSimon.size(); i++) {
//Here the pause should be
if(secuenciaSimon.get(i) != secuenciaUsuarioGUI.get(i)){
System.out.println("Not equal");
return false;
}
}
System.out.println("Equal");
puntuacion += 100; //Score
secuenciaUsuarioGUI.clear(); //Clears the LinkedList From the user
return true;
}
TL;博士在不冻结程序的情况下运行更多代码之前,需要等待 GUI 上按钮的n"次输入.
TL;DR Need to wait for "n" inputs of a button on a GUI before running more code without freezing the program.
谢谢
推荐答案
使用 int count 变量,将其设置为 0,并在每次按下按钮时递增.仅在计数足够时执行您的操作,即当它 == 3 时.
Use an int count variable, set it to 0, and increment it with each button press. Only do your action when the count is adequate, i.e., when it == 3.
例如
// this is a class field
private int count = 0;
// in the code where you create your GUI
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt){
count++; // increment count
// do something with the button pressed, add information to a list
secuenciaUsuarioGUI.add(/* ?? something ?? */);
if (count == 3) {
// check the sequence
comparaSecuencia(); // ?? maybe this
count = 0; // reset
}
}
});
一个关键概念是您的代码必须事件驱动.你不是在创建一个线性控制台程序,很多曾经在 for 循环中的代码不再在 for 循环中,而是在事件发生时增加计数器或改变对象的状态,然后对状态变化做出反应.
A key concept is that you must make your code event-driven. You're not creating a linear console program and so much code that used to be in for loops are no longer in for loops, but rather you will increment counters or change your object's state when an event occurs and then react to that change in state.
注意:如果您正在监听用户按下 JButton,请不要使用 MouseListener,而应使用 ActionListener.
Note: if you're listening for the user to press a JButton, don't use a MouseListener but rather an ActionListener.
这篇关于在 Java Swing 中等待多个按钮输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!