java keylistener 未调用

标签 java swing keylistener key-bindings

我在Java中使用KeyListener编写了示例代码, 我创建了一个 JPanel,然后将其 focusable 设置为 true,我创建了一个 KeyListener,请求焦点,然后将 KeyListener 添加到我的面板中。但 keyListener 的方法永远不会被调用。看起来虽然我请求了焦点,但它没有焦点。

有人可以帮忙吗?

listener = new KeyLis();
this.setFocusable(true);
this.requestFocus();
this.addKeyListener(listener);

 class KeyLis implements KeyListener{

    @Override
    public void keyPressed(KeyEvent e) {
        currentver += 5;
         switch (e.getKeyCode()) {
            case KeyEvent.VK_LEFT : if(horizontalyInBounds()) currentPos-= 5;  
                 break;
            case KeyEvent.VK_RIGHT: if(horizontalyInBounds()) currentPos+= 5;  
                 break;
        }
        repaint();
    }

    @Override
    public void keyReleased(KeyEvent e) {
        // TODO Auto-generated method stub

    }

    @Override
    public void keyTyped(KeyEvent e) {
    }
}

如果需要任何可运行的代码:

  import java.awt.Color;
  import java.awt.Graphics;
  import java.util.Random;

  import javax.swing.JFrame;
  import javax.swing.JLabel;


 public class test extends JFrame {

private AreaOfGame areaOfGame;

public test()
{
    super("");
    setVisible(true);
    this.setBackground(Color.darkGray);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.pack();
    setLayout(null);
    setBounds(200, 10, 400, 700);

    areaOfGame = new AreaOfGame();
    this.add(areaOfGame);

    startGame();
}

public int generateNext()
{
    Random r = new Random();
    int n = r.nextInt(7);
    return n;
}

public void startGame()
{
    while(!areaOfGame.GameOver())
    {
        areaOfGame.startGame(generateNext());
    }
}


public static void main(String[] args) {
    new MainFrame();
}


import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import javax.swing.JPanel;

public class AreaOfGame extends JPanel {


    private static final int rightside = 370;

    private int bottom;
    private int top;

    private int currentPos;
    private int currentver;
    private KeyLis listener;

    public AreaOfGame()
    {
        super();

        bottom = 650;
        top = 50;
        setLayout(null);
        setBounds(20, 50, 350, 600);
        setVisible(true);


        this.setBackground(Color.lightGray);

        listener = new KeyLis();
        this.setFocusable(true);
        if(this.requestFocus(true))
            System.out.println("true");;
        this.addKeyListener(listener);


        currentPos = 150;
        currentver=0;
    }

    public void startGame(int n)
    {
        while(verticallyInBound()){
            System.out.println("anything");

        }


    }

    public boolean verticallyInBound()
    {
        if(currentPos<= bottom -50)
            return true;
        return false;
    }


    public boolean GameOver()
    {
        if(top>= bottom){
            System.out.println("game over");
            return true;
        }

        else return false;
    }


    public boolean horizontalyInBounds()
    {
        if(currentPos<=rightside && currentPos>= 20)
            return true;
        else return false;
    }


class KeyLis implements KeyListener{

        @Override
        public void keyPressed(KeyEvent e) {
            System.out.println("called");
            currentver += 5;
             switch (e.getKeyCode()) {
                case KeyEvent.VK_LEFT : if(horizontalyInBounds()) currentPos-= 5;  break;
                case KeyEvent.VK_RIGHT: if(horizontalyInBounds()) currentPos+= 5;  break;
            }
            repaint();


        }

        @Override
        public void keyReleased(KeyEvent e) {
            // TODO Auto-generated method stub

        }

        @Override
        public void keyTyped(KeyEvent e) {
            System.out.println("called 3");
        }
}

}

最佳答案

我敢打赌,您在 JPanel 渲染之前请求焦点(在顶级窗口使用 pack()setVisible(true) 之前)称为),如果是这样,这将不起作用。焦点请求只有在组件渲染后才可能被授予。您是否检查过对 requestFocus() 的调用返回了什么?它必须返回 true,您的调用才有机会成功。另外,最好使用 requestFocusInWindow() 而不是 requestFocus()

但更重要的是,您不应该为此使用 KeyListener,而应该使用键绑定(bind),这是 Swing 本身用来响应按键的一个更高级别的概念。

编辑
SSCCE 的示例:

import java.awt.Dimension;
import java.awt.event.*;
import javax.swing.*;

public class TestKeyListener extends JPanel {
   private KeyLis listener;

   public TestKeyListener() {
      add(new JButton("Foo")); // something to draw off focus
      listener = new KeyLis();
      this.setFocusable(true);
      this.requestFocus();
      this.addKeyListener(listener);
   }

   @Override
   public Dimension getPreferredSize() {
      return new Dimension(300, 200);
   }

   private class KeyLis extends KeyAdapter {
      @Override
      public void keyPressed(KeyEvent e) {
         switch (e.getKeyCode()) {
         case KeyEvent.VK_LEFT:
            System.out.println("VK_LEFT pressed");
            break;
         case KeyEvent.VK_RIGHT:
            System.out.println("VK_RIGHT pressed");
            break;
         }
      }
   }

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

      JFrame frame = new JFrame("TestKeyListener");
      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();
         }
      });
   }
}

编辑2
以及等效的 SSCCE使用键绑定(bind):

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

@SuppressWarnings("serial")
public class TestKeyBindings extends JPanel {

   public TestKeyBindings() {
      add(new JButton("Foo")); // something to draw off focus
      setKeyBindings();
   }

   private void setKeyBindings() {
      ActionMap actionMap = getActionMap();
      int condition = JComponent.WHEN_IN_FOCUSED_WINDOW;
      InputMap inputMap = getInputMap(condition );

      String vkLeft = "VK_LEFT";
      String vkRight = "VK_RIGHT";
      inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), vkLeft);
      inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), vkRight);

      actionMap.put(vkLeft, new KeyAction(vkLeft));
      actionMap.put(vkRight, new KeyAction(vkRight));

   }

   @Override
   public Dimension getPreferredSize() {
      return new Dimension(300, 200);
   }

   private class KeyAction extends AbstractAction {
      public KeyAction(String actionCommand) {
         putValue(ACTION_COMMAND_KEY, actionCommand);
      }

      @Override
      public void actionPerformed(ActionEvent actionEvt) {
         System.out.println(actionEvt.getActionCommand() + " pressed");
      }
   }

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

      JFrame frame = new JFrame("TestKeyListener");
      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();
         }
      });
   }
}

编辑3
关于您最近的 SSCCE,您的 while (true) 循环正在阻塞您的 Swing 事件线程,并且可能会阻止用户交互或绘画的发生。最好使用 Swing 计时器,而不是 while (true)。例如:

import java.awt.*;
import java.awt.event.*;
import java.util.Random;

import javax.swing.*;

public class BbbTest extends JFrame {

   private AreaOfGame areaOfGame;

   public BbbTest() {
      super("");
//      setVisible(true);
      this.setBackground(Color.darkGray);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      this.pack();
      setLayout(null);
      setBounds(200, 10, 400, 700);

      areaOfGame = new AreaOfGame();
      this.add(areaOfGame);
      setVisible(true);

      startGame();
   }

   public int generateNext() {
      Random r = new Random();
      int n = r.nextInt(7);
      return n;
   }

   public void startGame() {
      // while (!areaOfGame.GameOver()) {
      // areaOfGame.startGame(generateNext());
      // }

      areaOfGame.startGame(generateNext());
   }

   public static void main(String[] args) {
      new BbbTest();
   }

   class AreaOfGame extends JPanel {

      private static final int rightside = 370;

      private int bottom;
      private int top;

      private int currentPos;
      private int currentver;
      private KeyLis listener;

      public AreaOfGame() {
         super();

         bottom = 650;
         top = 50;
         setLayout(null);
         setBounds(20, 50, 350, 600);
         setVisible(true);

         this.setBackground(Color.lightGray);

         listener = new KeyLis();
         this.setFocusable(true);
         if (this.requestFocus(true))
            System.out.println("true");
         ;
         this.addKeyListener(listener);

         currentPos = 150;
         currentver = 0;
      }

      public void startGame(int n) {
         // while (verticallyInBound()) {
         // System.out.println("anything");
         // }

         int timeDelay = 50; // msecs delay
         new Timer(timeDelay , new ActionListener() {

            public void actionPerformed(ActionEvent arg0) {
               System.out.println("anything");
            }
         }).start();

      }

      public boolean verticallyInBound() {
         if (currentPos <= bottom - 50)
            return true;
         return false;
      }

      public boolean GameOver() {
         if (top >= bottom) {
            System.out.println("game over");
            return true;
         }

         else
            return false;
      }

      public boolean horizontalyInBounds() {
         if (currentPos <= rightside && currentPos >= 20)
            return true;
         else
            return false;
      }

      class KeyLis implements KeyListener {

         @Override
         public void keyPressed(KeyEvent e) {
            System.out.println("called");
            currentver += 5;
            switch (e.getKeyCode()) {
            case KeyEvent.VK_LEFT:
               if (horizontalyInBounds())
                  currentPos -= 5;
               break;
            case KeyEvent.VK_RIGHT:
               if (horizontalyInBounds())
                  currentPos += 5;
               break;
            }
            repaint();

         }

         @Override
         public void keyReleased(KeyEvent e) {
            // TODO Auto-generated method stub

         }

         @Override
         public void keyTyped(KeyEvent e) {
            System.out.println("called 3");
         }
      }
   }
}

关于java keylistener 未调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59804596/

相关文章:

java - XPathFactory 不工作

java - 如何在 Swing 应用程序中隐藏光标?

java - 在 Java 中加载时镜像动画 gif - ImageIcon

java - 从 JTextField 创建 'BufferedReader'

Java event.getKeyCode 错误

java - 为什么按键监听器不起作用?

Java KeyListener 不起作用,我认为它与 addKeyListener() 有关;方法我不知道为什么

java - Android WiFi 状态未知

java - 读取 JSR223 断言到 Java 代码的响应

Java 命令 lastModified() 在 Clojure 中不起作用