键盘没有输入任何东西java

时间:2014-05-02 18:21:12

标签: java swing focus jpanel keylistener

我一直在尝试这段代码并对其进行编辑,但它不起作用。 假设将键盘输入存储在变量" c"然后比较一下 到键盘上的键。然后根据按下的键移动一个小方块。 键盘似乎没有被识别。有人可以帮帮我吗? 请注意我14岁所以请不要说它是多么简单和容易,我还在学习,你也可以用我可能理解的方式写它。提前谢谢

'package package1;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;

public class Class1 extends JPanel implements KeyListener, ActionListener{

Timer timer = new Timer(5, this);

//variables    
int cox = 0;
int spx = 0;  //cox = coordinates x, spx = speedx
int coy = 0;
int spy = 0;  //coy = coordinates y, spy = speedy

public void paintComponent(Graphics g)
{
    timer.start();

    super.paintComponent(g);
    g.setColor(Color.BLUE);     
    g.fillRect(cox, coy, 50, 50);

    addKeyListener(this);
    setFocusable(true);
    setFocusTraversalKeysEnabled(false);
}

public void actionPerformed(ActionEvent e)
{
    cox = cox + spx;
    coy = coy + spy;
    repaint();
}

public void keyPressed(KeyEvent e)
{
    int c = e.getKeyCode();

    if(c == KeyEvent.VK_LEFT)
    {
        spx = -1;
        spy = 0;
    }
    if(c == KeyEvent.VK_UP)
    {
        spx = 0;
        spy = -1;
    }
    if(c == KeyEvent.VK_RIGHT)
    {
        spx = 1;
        spy = 0;
    }
    if(c == KeyEvent.VK_DOWN)
    {
        spx = 0;
        spy = 1;
    }

}

public void keyTyped(KeyEvent e)
{
}
public void keyReleased(KeyEvent e)
{
    spx = 0;
    spy = 0;
}

public static void main(String args[])
{
    Class1 t = new Class1();
    JFrame frame = new JFrame("window");
    frame.setSize(500,500);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(t);
}
}

1 个答案:

答案 0 :(得分:3)

代码问题:

  • KeyListeners是非常低级的构造,通常应该避免使用大多数 Swing应用程序中的键绑定。这样做也可以更容易地解决困扰KeyListeners的焦点问题,并且导致当前的KeyListener无所事事。如果你在这个用Swing和KeyListeners标记的网站上阅读了大多数问题,你会一次又一次地看到这个建议 - 因为它是真的,而且它有效。
  • 请理解paintComponent(Graphics g)方法仅用于绘制 。它经常被调用,通常不受你的控制,因为操作系统可以诱使它被调用。
  • paintComponent方法对GUI的感知响应性有重大影响,因为它可以控制绘制GUI以及GUI可能包含的任何动画。如果任何原因的速度变慢,那么您的GUI看起来会很慢。
  • 因此,此方法应该用于绘图,只能用于绘图和 绘图。特别,
    • 不要从此方法中启动Swing Timer
    • 不要在此方法中添加KeyListener(除非您要向GUI添加20次KeyListener,这将导致极不可预测的行为),
    • 不要更改此方法中任何对象的状态。

例如:

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.Map;

import javax.swing.*;

@SuppressWarnings("serial")
public class Class1B extends JPanel {   
   private static final int PREF_W = 500;
   private static final int PREF_H = PREF_W;
   private static final int ANIMATION_DELAY = 15;
   private static final int RECT_WIDTH = 15;
   private static final Color RECT_COLOR = Color.red;
   private EnumMap<Direction, Boolean> dirMap = new EnumMap<>(Direction.class);
   private Map<Integer, Direction> keyToDir = new HashMap<>();
   private Timer animationTimer;
   public int rectX;
   public int rectY;


   public Class1B() {
      for (Direction dir : Direction.values()) {
         dirMap.put(dir, Boolean.FALSE);
      }
      keyToDir.put(KeyEvent.VK_UP, Direction.UP);
      keyToDir.put(KeyEvent.VK_DOWN, Direction.DOWN);
      keyToDir.put(KeyEvent.VK_LEFT, Direction.LEFT);
      keyToDir.put(KeyEvent.VK_RIGHT, Direction.RIGHT);
      setKeyBindings();

      animationTimer = new Timer(ANIMATION_DELAY, new AnimationListener());
      animationTimer.start();
   }

   @Override
   public Dimension getPreferredSize() {
      return new Dimension(PREF_W, PREF_H);
   }

   @Override
   protected void paintComponent(Graphics g) {
      super.paintComponent(g);
      g.setColor(RECT_COLOR);
      g.fillRect(rectX, rectY, RECT_WIDTH, RECT_WIDTH);
   }

   private void setKeyBindings() {
      int condition = WHEN_IN_FOCUSED_WINDOW;
      final InputMap inputMap = getInputMap(condition);
      final ActionMap actionMap = getActionMap();
      boolean[] keyPressed = { true, false };
      for (Integer keyCode : keyToDir.keySet()) {
         Direction dir = keyToDir.get(keyCode);
         for (boolean onKeyPress : keyPressed) {
            boolean onKeyRelease = !onKeyPress;
            KeyStroke keyStroke = KeyStroke.getKeyStroke(keyCode, 0,
                  onKeyRelease);
            Object key = keyStroke.toString();
            inputMap.put(keyStroke, key);
            actionMap.put(key, new KeyBindingsAction(dir, onKeyPress));
         }
      }
   }

   private class KeyBindingsAction extends AbstractAction {
      private Direction dir;
      boolean pressed;

      public KeyBindingsAction(Direction dir, boolean pressed) {
         this.dir = dir;
         this.pressed = pressed;
      }

      @Override
      public void actionPerformed(ActionEvent evt) {
         dirMap.put(dir, pressed);
      }
   }

   private class AnimationListener implements ActionListener {
      @Override
      public void actionPerformed(ActionEvent evt) {
         boolean repaint = false;
         for (Direction dir : Direction.values()) {
            if (dirMap.get(dir)) {
               rectX += dir.getIncrX();
               rectY += dir.getIncrY();
               repaint = true;
            }
         }
         if (repaint) {
            repaint();
         }
      }
   }

   private static void createAndShowGui() {
      Class1B mainPanel = new Class1B();

      JFrame frame = new JFrame("Class1B");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

enum Direction {
   UP(0, -1), DOWN(0, 1), LEFT(-1, 0), RIGHT(1, 0);
   private int incrX;
   private int incrY;

   private Direction(int incrX, int incrY) {
      this.incrX = incrX;
      this.incrY = incrY;
   }

   public int getIncrX() {
      return incrX;
   }

   public int getIncrY() {
      return incrY;
   }
}