等待Java Swing中的多个按钮输入

时间:2013-05-05 20:07:54

标签: java swing user-interface wait

抱歉,我的英语不好,不是母语。我正在GUI中使用Java上的SimonSays游戏。我是新编码。我设法使应用程序在控制台上运行,但是它以图形方式工作一团糟。程序将生成的序列(secuenciaSimon)中的LinkedLists与用户通过按钮(secuenciaUsuarioGUI)输入的序列进行比较但是,问题是通过单击任何按钮调用compare方法,因此simon生成的Sequence中的LinkedList比用户引入的更大。

黄色按钮代码

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; DR 在运行更多代码之前,需要等待GUI上按钮的“n”输入而不冻结程序。

由于

1 个答案:

答案 0 :(得分:2)

使用int count变量,将其设置为0,并在每次按下按钮时递增它。只有在计数足够时才进行操作,即当它= = 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循环,而是在事件发生时增加计数器或改变对象的状态,然后对状态的变化作出反应

注意:如果您正在监听用户按JButton,请不要使用MouseListener而是使用ActionListener。