简体   繁体   English

KeyListener在Java swing中没有响应

[英]KeyListener not responding in Java swing

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, the KeyListener is not responding. 但是在这个新窗口中,KeyListener没有响应。 If I click back to the Main Menu window, the KeyListener is still working there. 如果我单击返回主菜单窗口,KeyListener仍然在那里工作。 Here is the code: 这是代码:

MainMenu: 主菜单:

import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.swing.*;
import java.io.*;
import javax.imageio.*;

public class DisplayMainMenu extends JFrame implements KeyListener{

  static int width = 799, height = 463;
  int arrowPos = 310;
  boolean clear = true;
  BufferedImage menu = null;
  BufferedImage arrow = null;
  LevelSkip test = new LevelSkip();
  boolean done = false;
  static DisplayMainMenu main;

  public static void main(String[] args){
    main = new DisplayMainMenu();
    main.setResizable(false);
    main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    main.setVisible(true);
    main.init();
  }

  public void init() {
    try{
      menu = ImageIO.read(new File("Main Menu.png"));
      arrow = ImageIO.read(new File("arrow.png"));
    }catch(IOException ie) {
      System.out.println(ie.getMessage());
    }
    this.setSize(width, height);
    this.addKeyListener(this);
    clear = true;
    paint(getGraphics());
  }

  public void paint (Graphics g){
    if(clear==true){
      g.drawImage(menu,0,0,null);
      clear = false;
    }
    g.drawImage(arrow,275,arrowPos,null);
  }
  public void keyPressed(KeyEvent e){
    String key = e.getKeyText(e.getKeyCode());
    if(key == "Up"){
      clear = true;
      if (arrowPos > 310)
        arrowPos -= 30;
      else
        arrowPos = 370;
      paint(getGraphics());
    }
    if(key == "Down"){
      clear = true;
      if (arrowPos < 370)
        arrowPos += 30;
      else
        arrowPos = 310;
      paint(getGraphics());
    }
    if(key == "Space"){
      done = true;
      switch(arrowPos){
        case 310:  System.out.println("RUN NEW GAME"); test.init();
          break;
        case 340:  System.out.println("RUN HIGH SCORES");
          break;
        case 370:  System.exit(0);
      }
    }
  }
  public void keyReleased(KeyEvent e) {}
  public void keyTyped(KeyEvent e) {}
}

LevelSkip: LevelSkip:

import java.awt.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.swing.*;
import java.io.*;
import javax.imageio.*;

public class LevelSkip extends JFrame implements KeyListener {

  static int width = 799, height = 463;
  int arrowPos = 109;
  boolean clear = true;
  BufferedImage menu = null;
  BufferedImage arrow = null;

  public void init() {
    LevelSkip main = new LevelSkip();
    main.setSize(width, height);
    main.requestFocusInWindow();
    main.addKeyListener(main);
    main.setResizable(false);
    main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    main.setVisible(true);
    try{
      menu = ImageIO.read(new File("level skip.png"));
      arrow = ImageIO.read(new File("arrow2.png"));
    }catch(IOException ie) {
      System.out.println(ie.getMessage());
    }
    clear = true;
    paint(main.getGraphics());
  }

  public void paint (Graphics g){
    if(clear==true){
      g.drawImage(menu,0,0,null);
      clear = false;
    }
    g.drawImage(arrow,arrowPos,355,null);
  }
  public void keyPressed(KeyEvent e){
    String key = e.getKeyText(e.getKeyCode());
    if(key == "Left"){
      clear = true;
      if (arrowPos > 109)
        arrowPos -= 260;
      else
        arrowPos = 629;
      paint(getGraphics());
    }
    if(key == "Right"){
      clear = true;
      if (arrowPos < 629)
        arrowPos += 260;
      else
        arrowPos = 109;
      paint(getGraphics());
    }
    if(key == "Space"){
      switch(arrowPos){
        case 109:  System.out.println("ADD 1 TO LEVEL AND RUN BATTLE");
        break;
        case 369:  System.out.println("ADD 5 TO LEVEL AND RUN BATTLE");
        break;
        case 629:  System.out.println("ADD 10 TO LEVEL AND RUN BATTLE");
      }
    }
  }
  public void keyReleased(KeyEvent e) {}
  public void keyTyped(KeyEvent e) {}

}

I'm not exactly sure what the problem is, the Level Skip window displays fine, it just doesn't register any key presses. 我不确定问题是什么,Level Skip窗口显示正常,它只是没有注册任何按键。

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 . 90%的解决方案是使用密钥绑定

Your other problem is that you're comparing Strings == . 你的另一个问题是你在比较Strings == You don't want to do this. 你不想这样做。 Use the equals or the equalsIgnoreCase(...) method instead. 请改用equals或equalsIgnoreCase(...)方法。 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. 直接调用paint(...) ,你几乎不应该做的事情。
  • 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. 绘制顶层窗口的paint(...)方法,您也应避免使用它,而不是在JPanel(或其他JComponent) paintComponent(...)方法中绘图。
  • Not calling the paint or paintComponent's super method at the start of the method 在方法的开头不调用paint或paintComponent的super方法
  • Putting program logic in a paint or paintComponent method. 将程序逻辑放在paint或paintComponent方法中。
  • etc... 等等...

You will want to go through the Swing tutorials before going much further to learn from the pros. 在进一步向专业人士学习之前,您将需要阅读Swing教程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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