KeyListener not responding in Java swing

前端 未结 1 1235
庸人自扰
庸人自扰 2020-12-11 23:31

I\'m making a game, and I have a Main Menu that works perfectly. When I select one of the options, it brings up another Menu in a new window. However in this new window, t

相关标签:
1条回答
  • 2020-12-12 00:03

    If you've searched on this problem at all, you'll see that it almost always means that the component being listened to doesn't have focus. 90% of the time the solution is to use Key Bindings.

    Your other problem is that you're comparing Strings ==. You don't want to do this. Use the equals or the equalsIgnoreCase(...) method instead. Understand that == checks if the two objects are the same which is not what you're interested in. The methods on the other hand check if the two Strings have the same characters in the same order, and that's what matters here. So instead of

    if (fu == "bar") {
      // do something
    }
    

    do,

    if (fu.equals("bar")) {
      // do something
    }
    

    or,

    if (fu.equalsIgnoreCase("bar")) {
      // do something
    }
    

    You're also

    • calling paint(...) directly, something you should almost never do.
    • Drawing in a top level window's paint(...) method which you also should avoid instead of drawing in a JPanel's (or other JComponent) paintComponent(...) method.
    • Not calling the paint or paintComponent's super method at the start of the method
    • Putting program logic in a paint or paintComponent method.
    • etc...

    You will want to go through the Swing tutorials before going much further to learn from the pros.

    0 讨论(0)
提交回复
热议问题