简体   繁体   中英

How to ask user to press any key to continue with conditions in java?

I have this code, what I want to do is only when the program is launched, the user should be able to press enter, and only once... until relaunch.

I have this label with text called JLabel info = new JLabel("press enter to continue"); , when the user presses enter then the text of this will change and enter keypress enter should not function anymore, only when the program launches the user can press enter.

addKeyListener(new KeyAdapter() {
   public void keyPressed(KeyEvent arg0) {
      if(e.getKeyChar() == e.VK_ENTER)
   }
});

After the action (pressing Enter) happened you could remove the KeyListener from the Component. You can look here for an example on how to remove the listener from a JPanel. I adjusted the code from the example a little bit:

KeyAdapter keyAdapter = new KeyAdapter() {
  public void keyPressed(KeyEvent e)
  {
    if(e.getKeyChar() == e.VK_ENTER)
      ....
    }

  }
};

// Register the listener with this JPanel
addKeyListener(keyAdapter);

// Remove the listener from this JPanel
removeKeyListener(keyAdapter);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM