Search code examples
javaoopjavafxevent-handlingmouseevent

How do I link these two Mouse events? JavaFx


I am currently working on a project which requires linking two mouse events. The game consists in comparing two moving balloons from lots of balloons on the screen. The instructions are:

  1. I click a balloon which has text in English (mouse event 1), balloon should stop and I should get the string of the text kept somewhere
  2. I click a balloon which has text in Spanish (mouse event 2), balloon should stop and I should get the string of the text kept somewhere
  3. Text in English gets compared with text in Spanish after that click

If the translation of the word is correct, the balloons fade away and I don't lose lives ("lives" are rectangles on a HBox), otherwise I lose lives and the balloons fade away.

The other thing that came to my mind was:

  1. Click balloon, balloon stops (mouse event 1)
  2. Click balloon, balloon stops (mouse event 2)

The program should know I have clicked those two balloons. Then I could use a method to compare the balloons to check if the translation was wrong or right and make them fade away.


Solution

  • You should add an EventHandler to each baloon and keep track if is the first or second ballon using another variable. Something like this:

    public class ViewController {
    
      private String savedStr;
    
      public void init() {
        for (Baloon baloon : baloons) {
            baloon.setOnMouseClicked(event -> {
                if (savedStr == null) { // Mouse Event 1
                  savedStr = baloon.getString());
                } else { // Mouse Event 2
                  checkTranslation(savedStr, baloon.getString());
                  savedStr  = null;
                }
            }
        }
      }
    }