7

我在让我KeyBoardFocusManger的全屏工作时遇到问题Window。无论如何,它只是不会获得键盘输入。我使用 aSystem.exit(0)和 aprintln()来查找对 keypressed/released/typed 方法的任何调用,但没有引发错误。我试过了KeyListeners;但是在我读完这个之后,我改成了 a KeyboardFocusManager,同样的事情仍然发生。我真的很绝望;从我的判断Window来看,键盘没有得到焦点?

这是我的主要内容:

public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {

        @Override
        public void run() {
            // Determine if full-screen mode is supported directly
            GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
            GraphicsDevice gs = ge.getDefaultScreenDevice();
            if (gs.isFullScreenSupported()) {
                Frame frame = new Frame(gs.getDefaultConfiguration());
                SpaceInvaderUI spaceInvaderUI = new SpaceInvaderUI(frame);
                // Enter full-screen mode
                gs.setFullScreenWindow(spaceInvaderUI);
            } else {
                JOptionPane.showMessageDialog(null, "Does not support full screen!", "Error 0x01", JOptionPane.ERROR_MESSAGE);
                System.exit(1);
            }
        }
    });
}

这是包含KeyBoardFocusManger, 并添加到addListeners()方法中的 UI:

class SpaceInvaderUI extends Window {

    private JPanel drawingPanel;
    private Image background;
    private JButton btnExit;

    public SpaceInvaderUI(Frame frame) {
        super(frame);
        try {
            background = ImageIO.read(getClass().getResourceAsStream("background.png"));
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, "Could not extract resource: " + ex.getMessage(), "Error 0x02", JOptionPane.ERROR_MESSAGE);
            System.exit(2);
        }
        createWindow();
    }

    private void createComponents() throws HeadlessException {
        drawingPanel = new DrawingPanel(background, this);
        btnExit = new JButton("Exit");
    }

    private void createWindow() {
        createComponents();
        addListeners();
        addComponentsToWindow();
    }

    private void addComponentsToWindow() {
        add(drawingPanel, BorderLayout.CENTER);
        add(btnExit, BorderLayout.SOUTH);
    }

    private void addListeners() {
        KeyboardFocusManager manager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
        manager.addKeyEventDispatcher(new MyDispatcher());
        btnExit.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent ae) {
                System.exit(0);
            }
        });
    }

    private class MyDispatcher implements KeyEventDispatcher {

        @Override
        public boolean dispatchKeyEvent(KeyEvent e) {
            if (e.getID() == KeyEvent.KEY_PRESSED) {
                System.out.println("pressed");
                System.exit(0);
            } else if (e.getID() == KeyEvent.KEY_RELEASED) {
                System.out.println("released");
                System.exit(0);
            } else if (e.getID() == KeyEvent.KEY_TYPED) {
                System.out.println("Typed");
                System.exit(0);
            }
            return false;
        }
    }
}

退出按钮只是因为我厌倦了通过任务管理器杀死我的应用程序。最后,这是我的面板,游戏将在上面进行,我的背景画在上面:

public class DrawingPanel extends JPanel {

    private final Image background;
    private final SpaceInvaderUI invaderUI;

    DrawingPanel(Image background, SpaceInvaderUI invaderUI) {
        this.background = background;
        this.invaderUI = invaderUI;
    }

    @Override
    protected void paintComponent(Graphics grphcs) {
        super.paintComponent(grphcs);
        grphcs.drawImage(background.getScaledInstance((int) invaderUI.getWidth(), (int) invaderUI.getHeight(), Image.SCALE_SMOOTH), 0, 0, this);
    }
}

先感谢您。

编辑:我现在尝试在我的上使用键绑定,drawingPanel但当我按f2时仍然没有任何反应:

class SpaceInvaderUI extends Window {

    private JPanel drawingPanel;
    private Image background;
    private JButton btnExit;

    public SpaceInvaderUI(Frame frame) {
        super(frame);
        try {
            background = ImageIO.read(getClass().getResourceAsStream("background.png"));
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, "Could not extract resource: " + ex.getMessage(), "Error 0x02", JOptionPane.ERROR_MESSAGE);
            System.exit(2);
        }
        createWindow();
    }

    private void createComponents() throws HeadlessException {
        drawingPanel = new DrawingPanel(background, this);
        btnExit = new JButton("Exit");
    }

    private void createWindow() {
        createComponents();
        addListeners();
        addComponentsToWindow();
    }

    private void addComponentsToWindow() {
        add(drawingPanel, BorderLayout.CENTER);
        add(btnExit, BorderLayout.SOUTH);
    }

    private void addListeners() {
        Action exit = new AbstractAction() {

            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        };
        drawingPanel.getInputMap().put(KeyStroke.getKeyStroke("F2"),
                exit);
        btnExit.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent ae) {
                System.exit(0);
            }
        });
    }
}
4

2 回答 2

5

为什么在 Swing GUI 中使用 AWT 组件?我担心(但不确定)这样做,您可能会失去一些 Swing 功能。

如果您仅捕获选择键选择键击来控制游戏,请考虑使用Key Bindings

编辑
不,AWT 组件没有错,但仍然可能不应该使用。

编辑 2
由于某种原因,您的顶级窗口没有聚焦。继续测试代码...

编辑 3
使用 JFrame 对我有用:

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

public class Test3 {
   public static void main(String[] args) {
      EventQueue.invokeLater(new Runnable() {

         @Override
         public void run() {
            GraphicsEnvironment ge = GraphicsEnvironment
                  .getLocalGraphicsEnvironment();
            GraphicsDevice gs = ge.getDefaultScreenDevice();
            if (gs.isFullScreenSupported()) {
               SpaceInvaderUI spaceInvaderUI = new SpaceInvaderUI(gs.getDefaultConfiguration());
               gs.setFullScreenWindow(spaceInvaderUI);
            } else {
               JOptionPane.showMessageDialog(null,
                     "Does not support full screen!", "Error 0x01",
                     JOptionPane.ERROR_MESSAGE);
               System.exit(1);
            }
         }
      });
   }
}

// class SpaceInvaderUI extends JWindow {
class SpaceInvaderUI extends JFrame {

   private JPanel drawingPanel;
   private Image background;
   private JButton btnExit;

   public SpaceInvaderUI(GraphicsConfiguration gc) {
      super(gc);
      createWindow();
      addKeyBindings();
      setUndecorated(true);
   }

   private void addKeyBindings() {
      int condition = JPanel.WHEN_IN_FOCUSED_WINDOW;
      InputMap inputMap = drawingPanel.getInputMap(condition );
      ActionMap actionMap = drawingPanel.getActionMap();

      boolean released = false;
      KeyStroke upArrowKeyStrokePressed = KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0, released );
      String upArrowPressed = "up arrow pressed";
      inputMap.put(upArrowKeyStrokePressed , upArrowPressed);
      actionMap.put(upArrowPressed, new AbstractAction() {

         @Override
         public void actionPerformed(ActionEvent arg0) {
            System.out.println("up arrow pressed");
         }
      });

      released = true;
      String upArrowReleased = "up arrow released";
      KeyStroke upArrowKeyStrokeReleased = KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0, released );
      inputMap.put(upArrowKeyStrokeReleased , upArrowReleased);
      actionMap.put(upArrowReleased , new AbstractAction() {

         @Override
         public void actionPerformed(ActionEvent arg0) {
            System.out.println("up arrow released");
         }
      });

   }

   private void createComponents() throws HeadlessException {
      drawingPanel = new DrawingPanel(background, this);
      btnExit = new JButton("Exit");
   }

   private void createWindow() {
      createComponents();
      addListeners();
      addComponentsToWindow();
   }

   private void addComponentsToWindow() {
      add(drawingPanel, BorderLayout.CENTER);
      add(btnExit, BorderLayout.SOUTH);
   }

   private void addListeners() {
//      KeyboardFocusManager manager = KeyboardFocusManager
//            .getCurrentKeyboardFocusManager();
//      manager.addKeyEventDispatcher(new MyDispatcher());
      btnExit.addActionListener(new ActionListener() {

         @Override
         public void actionPerformed(ActionEvent ae) {
            System.exit(0);
         }
      });
   }
//
//   private class MyDispatcher implements KeyEventDispatcher {
//
//      @Override
//      public boolean dispatchKeyEvent(KeyEvent e) {
//         System.out.println("in dispatch. KeyEvent := " + e);
//         if (e.getID() == KeyEvent.KEY_PRESSED) {
//            System.out.println("pressed");
//            System.exit(0);
//         } else if (e.getID() == KeyEvent.KEY_RELEASED) {
//            System.out.println("released");
//            System.exit(0);
//         } else if (e.getID() == KeyEvent.KEY_TYPED) {
//            System.out.println("Typed");
//            System.exit(0);
//         }
//         return false;
//      }
//   }
}

class DrawingPanel extends JPanel {

   private final Image background;
   private final SpaceInvaderUI invaderUI;

   DrawingPanel(Image background, SpaceInvaderUI invaderUI) {
      this.background = background;
      this.invaderUI = invaderUI;
      setBackground(Color.pink);
   }

   @Override
   protected void paintComponent(Graphics grphcs) {
      super.paintComponent(grphcs);
   }
}
于 2012-06-24T16:13:04.597 回答
4

如this related 所示,您可以对按钮键绑定FullScreenTest使用相同的Action实例。

附录:@nIcE cOw 问,我们可以通过使用and来添加多个键并使用同一个吗?JComponent InputMap ActionMap AbstractAction

是的,多个键绑定是可能的;我有时会调用doClick()以获得视听反馈,如此处所示

于 2012-06-24T16:48:24.817 回答