KeyListener在Java Swing中没有响应 [英] KeyListener not responding in Java swing

查看:84
本文介绍了KeyListener在Java Swing中没有响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个游戏,并且我有一个主菜单,可以很好地工作.当我选择一个选项时,它将在新窗口中弹出另一个菜单.但是,在这个新窗口中,KeyListener没有响应.如果我单击回到主菜单"窗口,则KeyListener仍在那儿工作.这是代码:

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. If I click back to the Main Menu window, the KeyListener is still working there. 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.

推荐答案

如果您完全搜索了此问题,您会发现它几乎总是意味着正在收听的组件没有焦点. 90%的解决方案是使用键绑定.

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.

您的另一个问题是您正在比较字符串==.您不想这样做.请改用equals或equalsIgnoreCase(...)方法.理解==检查两个对象是否相同,这不是您感兴趣的.另一方面,方法检查两个Strings是否具有相同顺序的相同字符,并且这才是最重要的.因此,而不是

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
}

做,

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

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

您也是

  • 直接调用paint(...),几乎是您永远不应该做的事情.
  • 在顶层窗口的paint(...)方法中绘制,您也应该避免,而不是在JPanel(或其他JComponent)的paintComponent(...)方法中绘制.
  • 在方法开始时未调用paint或paintComponent的super方法
  • 将程序逻辑放入paint或paintComponent方法中.
  • 等...
  • 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...

在进一步学习专家之前,您需要先阅读Swing教程.

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

这篇关于KeyListener在Java Swing中没有响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆