I have just created a java tic-tac-toe game i would like to figure out how to run a method once the enter key is pressed during a certain condition an example is below...
if(/*condition is met*/){
//keyListener
}
I have just created a java tic-tac-toe game i would like to figure out how to run a method once the enter key is pressed during a certain condition an example is below...
if(/*condition is met*/){
//keyListener
}
One way is to implement the
KeyListener
interface and its key event methods. For example,Then add this listener with
Or if you prefer,
See this for more details.
Depending on where you want to trap the "enter" key, you could use an
ActionListener
(on such components such as text components or buttons) or attach a key binding to you componentThis will rely on the component being focused.
Caveat - It's been a while since I did desktop applications, but the java.awt.Component class has an addKeyListener() method which you can use to register a class that implements KeyListener - is this what you are looking for?