0

I have a question about Java related with the class KeyListener which is used for the listening of keys. In my application firstly I display an introductory video with JavaFX toolkit. I set a KeyListener for the JFXPanel used for the video, and it works fine, it is able to read the keys that I press in the keyboard while the video is being played. But the problem is when the video ends (either because it finishes playing or because I stop it by making an interruption to a thread pressing the "Escape" key), that I try to add a new KeyListener to the main JFrame of the application and I am not able to read any key from it.

You should also ask yourself why I added a KeyListener to the JFXPanel and then after the video ends I add a new KeyListener to the main JFrame of the application, instead of adding only one KeyListener to the JFrame from the start. The reason is that if I do that, then I am not able to read any key while the video is being played, so someone suggested me to adding the KeyListener to the JFXPanel.

Here is all the code of my application:

/**
 * Main class of the application.
 */
public class Main{

  // Define the variable for the window of the game.
  public static JFrame window;

  // Define the variable for the introductory video.
  public static MediaPlayer video;

  // Define the variable for a thread.
  public static Thread thread;

  /**
   * Main function of the application.
   */
  public static void main(String[] args){

    // Create a Swing thread.
    SwingUtilities.invokeLater(new Runnable(){

      @Override
      public void run(){

        // Prevent the JavaFX toolkit from closing.
        Platform.setImplicitExit(false);

        // Create the window of the game.
        window = new JFrame();

        // Set the title.
        window.setTitle("Chip");

        // Set the resolution as 1920 x 1280.
        window.setSize(1926,1343);

        // Set the location as in the middle of the screen.
        window.setLocationRelativeTo(null);

        // Set the operation when the window closes.
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // Disable the maximization and resizable mode.
        window.setResizable(false);

        // Show the window.
        window.setVisible(true);

        // Create a key listener.
        KeyListener keyListener = createKeyListener();

        // Create a JavaFX panel.
        JFXPanel panelJavaFX = new JFXPanel();

        // Add the key listener to the JavaFX panel.
        panelJavaFX.addKeyListener(keyListener);

        // Create a JavaFX thread.
        Platform.runLater(new Runnable(){

          @Override
          public void run(){

            // Create a new thread.
            thread = new Thread(new Runnable(){

              public void run(){

                try{

                  // Show the introductory video.
                  showVideo(panelJavaFX);

                  // Pause the execution of the application for 30 seconds (duration of the introductory video).
                  Thread.sleep(30000);

                }catch (InterruptedException interruptedException){

                  // Stop the video if an interruption has been occurred.
                  video.stop();

                }

                // Set the background image.
                String filename = "./media/image/background.jpg";
                window.setContentPane(new JLabel(new ImageIcon(filename)));

                // Show the window.
                window.setVisible(true);

                // Add the key listener to the window of the game.
                window.addKeyListener(keyListener);

              }

            });

            // Start the execution of the thread.
            thread.start();

          }

        });

      }

    });

  }

  /**
   * Creates a key listener.
   * @return Key listener.
   */
  public static KeyListener createKeyListener(){

    // Create the key listener.
    KeyListener keyListener = new KeyListener(){

      // Set the behavior whenever a key is pressed.
      @Override
      public void keyPressed(KeyEvent keyEvent){

        // Check if the "Escape" key is pressed.
        if (keyEvent.getKeyCode() == KeyEvent.VK_ESCAPE){

          // Check if the introductory video it is being played.
          if (video.getStatus().equals(Status.PLAYING)){

            // Make an interruption in the thread that is being executed.
            thread.interrupt();

          }

        }

      }

      // Set the behavior whenever a key is released.
      @Override
      public void keyReleased(KeyEvent keyEvent){}

      // Set the behavior whenever a key is typed.
      @Override
      public void keyTyped(KeyEvent keyEvent){}

    };

    // Return the key listener.
    return keyListener;

  }

  /**
   * Shows the introductory video.
   * @param panelJavaFX JFXPanel used to display the video.
   */
  public static void showVideo(JFXPanel panelJavaFX){

    // Set the size of the JaxaFX panel as the resolution of the introductory video (1920 x 1080).
    panelJavaFX.setSize(1920,1080);

    // Set the location of the JavaFX panel as in the middle of the window of the game.
    int coordinateX = (window.getWidth() - panelJavaFX.getWidth() - window.getInsets().left - window.getInsets().right) / 2;
    int coordinateY = (window.getHeight() - panelJavaFX.getHeight() - window.getInsets().top - window.getInsets().bottom) / 2;
    panelJavaFX.setLocation(coordinateX,coordinateY);

    // Define the video file.
    String filename = "./media/video/introduction.mp4";
    video = new MediaPlayer(new Media(new File(filename).toURI().toString()));

    // Add the video to the JavaFX panel.
    panelJavaFX.setScene(new Scene(new Group(new MediaView(video))));

    // Add the JavaFX panel to the window of the game.
    window.getContentPane().setLayout(null);
    window.add(panelJavaFX);

    // Play the video.
    video.setAutoPlay(true);

  }

}
  • imports and all comments on each method is no usefull for all, by thanks to have indented well ;) – azro Jul 13 '17 at 12:24
  • @azro - well, at least this input should compile ... and should lead to a runable program easily. I have seen worse. A 100 times worse. Probably a 100 times during the last hours. – GhostCat Jul 13 '17 at 12:27
  • @GhostCat I know i know – azro Jul 13 '17 at 12:28
  • Sorry, I am new here. Which characteristics of the code you will recommend me to use? I mean in my question I should remove the imports and which comments? Thanks. – Néstor Llamas Jul 13 '17 at 12:31
  • Have you tried calling `requestFocus()` on the `JFXPanel`? – d.j.brown Jul 13 '17 at 12:32
  • @Néstor I think your input is ok. The best thing is a [mcve] - focus on *minimal* but *complete*. Your code seems to be *complete*, and yeah, maybe it could be 10 lines shorter. But as said: the quality of your input is *easily* in the top 5% of what I have seen here lately. – GhostCat Jul 13 '17 at 12:43
  • 1
    Possible duplicate of [Unresponsive KeyListener for JFrame](https://stackoverflow.com/questions/286727/unresponsive-keylistener-for-jframe) – Arnaud Jul 13 '17 at 12:44
  • @d.j.brown: Yeah, I added the instruction `window.requestFocus()` before the instruction `window.addKeyListener(keyListener)` and now it can read when the "Escape" key is pressed after the video has been played. So question solved. Thanks a lot! – Néstor Llamas Jul 14 '17 at 10:28

1 Answers1

0

The correct answer to this question is:

I added the instruction window.requestFocus() before the instruction window.addKeyListener(keyListener) and now it can read when the "Escape" key is pressed after the video has been played.