【问题标题】:Full Screen Exclusive Mode Key Input with just a Window只有一个窗口的全屏独占模式键输入
【发布时间】:2017-02-12 06:01:37
【问题描述】:

我正在开发一个使用全屏独占的小游戏,我需要能够接收玩家的键盘输入。

在我的程序中,我有一个设置为全屏独占的窗口和一个渲染循环。

窗口创建:

private void initialize() {
    //This is used for my game loop...
    running = true;

    //Create the instance variable 'window' here.
    window = new Window(null);
    //Ignoring OS paint requests...
    window.setIgnoreRepaint(true);
    //Set the window to full screen exclusive.
    GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().setFullScreenWindow(window);

    ...

游戏循环:

private void loop() {
    Graphics graphics = window.getGraphics();
    graphics.setColor(Color.CYAN);
    graphics.fillRect(0, 0, 1920, 1080);
    graphics.dispose();
}

我的进口:

import java.awt.Color;
import java.awt.Graphics;
import java.awt.GraphicsEnvironment;
import java.awt.Window;

现在,这工作正常。正如它应该的那样。它在我的屏幕上呈现一个青色矩形,但是,我需要能够检测用户何时按下键,例如点击Escape 关闭程序等等。我不知道该怎么做。 :(

我尝试将KeyListener 添加到我的window(没有用)。 我尝试将JPanel 添加到我的window 并添加一个监听器(也没有工作)。 我曾尝试请求关注我的JPanel 并在上面做同样的事情。 我尝试使用 KeyListener 制作JFrame,然后将其传递给我的window 的构造函数。 我尝试将带有键绑定的相同JFrame 传递给我的window,而不是KeyListener。

显然,以上都没有奏效。 (没有抛出错误,当我按下一个键或使用System.exit(int); 退出程序时,我根本无法让程序在我的sysouts 中输出文本)我已经取出了所有不起作用的东西我来自上面的代码;我目前有一个窗口和一个游戏循环。 如果有其他方法可以让我获得全屏独占的Key Input,请告诉我。(感觉好像有专门的全屏独占的常规方法,但我没有找到一个还没有。)或者如果你相信有一种方法可以得到我尝试过的方法之一,(也许你认为我做错了什么),请告诉我。 (此时我有点绝望了)。

【问题讨论】:

  • 我先看看How to Use Key Bindings,然后我鼓励你看看Painting in AWT and SwingPerforming Custom Painting,因为Graphics graphics = window.getGraphics();不是自定义绘画应该做的.我知道有人会建议它,但KeyListener 通常是一个糟糕的选择,因为它没有键绑定 API 的灵活性 - 恕我直言
  • 如果你想要更高级的东西,我还建议你看看 BufferStrategyBufferStrategy and BufferCapabilities (ps - Window 不是双缓冲的,所以你很可能遭受更新期间闪烁)
  • 如果你想知道为什么我不推荐KeyListener - this is another reason why
  • @MadProgrammer 感谢您的帮助!我确实浏览了您推荐给我的 Key Binding 页面,但它似乎对我不起作用,但我会继续尝试它。无论如何,我从this 页面找到了Graphics graphics = window.getGraphics();。我现在会看看你给我看的其他页面。
  • 你对信息的解释不正确(我没有这样做一千次),他们不使用getGraphics,他们使用返回Graphics实例的方法,是前面的双缓冲和翻页部分的前奏

标签: java window awt fullscreen


【解决方案1】:

使用键绑定的示例。真的很简单,还演示了DisplayMode的使用,如果你愿意的话,但是一旦它运行,只需按住空格,它就会更新,释放它,它会更新。双击关闭;)

import java.awt.DisplayMode;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;

public class Test {

    public static void main(String[] args) {
        JFrame f = new JFrame("Test");
        f.setUndecorated(true);
        f.add(new TestPane());
        f.setResizable(false);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        GraphicsDevice device = GraphicsEnvironment
                .getLocalGraphicsEnvironment().getDefaultScreenDevice();
        if (device.isFullScreenSupported()) {
            device.setFullScreenWindow(f);
            if (device.isDisplayChangeSupported()) {
                try {
                    List<DisplayMode> matchingModes = new ArrayList<>(25);

                    DisplayMode[] modes = device.getDisplayModes();
                    for (DisplayMode mode : modes) {
                        if (mode.getWidth() == 1280 && mode.getHeight() == 720) {
                            matchingModes.add(mode);
                        }
                    }

                    if (!matchingModes.isEmpty()) {
                        for (DisplayMode mode : matchingModes) {
                            try {
                                device.setDisplayMode(mode);
                                System.out.println(mode.getWidth() + "x" + mode.getHeight() + " " + mode.getBitDepth() + " @ " + mode.getRefreshRate());
                                break;
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    } else {
                        System.err.println("!! No matching modes available");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                System.err.println("Change display mode not supported");
            }
        } else {
            System.err.println("Full screen not supported");
        }
    }

    public static class TestPane extends JPanel {

        private boolean spaced = false;

        public TestPane() {
            addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    requestFocusInWindow(true);
                    if (e.getClickCount() == 2) {
                        SwingUtilities.windowForComponent(TestPane.this).dispose();
                    }
                }
            });

            InputMap im = getInputMap();
            ActionMap am = getActionMap();

            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0, false), "spaced-pressed");
            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0, true), "spaced-released");
            am.put("spaced-pressed", new AbstractAction() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    spaced = true;
                    repaint();
                }
            });
            am.put("spaced-released", new AbstractAction() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    spaced = false;
                    repaint();
                }
            });

            requestFocusInWindow(true);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            String text = getWidth() + "x" + getHeight();
            FontMetrics fm = g.getFontMetrics();
            int x = (getWidth() - fm.stringWidth(text)) / 2;
            int y = (getHeight() - fm.getHeight()) / 2;
            g.drawString(text, x, y + fm.getAscent());

            GraphicsDevice device = GraphicsEnvironment
                    .getLocalGraphicsEnvironment().getDefaultScreenDevice();

            DisplayMode mode = device.getDisplayMode();
            text = mode.getWidth() + "x" + mode.getHeight() + " " + mode.getBitDepth() + " @ " + mode.getRefreshRate();
            x = (getWidth() - fm.stringWidth(text)) / 2;
            y += fm.getHeight();
            g.drawString(text, x, y + fm.getAscent());

            text = "Spaced [" + spaced + "]";
            x = (getWidth() - fm.stringWidth(text)) / 2;
            y += fm.getHeight();
            g.drawString(text, x, y + fm.getAscent());
        }

    }
}

【讨论】:

  • 当我试图运行它时,它放大了我的屏幕,我无法点击任何东西。我认为框架是看不见的,但仍然覆盖了屏幕。但主要问题是它不会接收任何键/鼠标输入,所以我无法关闭它。 (此外,没有渲染任何内容)。无论如何,我 Alt+Tabbed 到我的 IDE 并退出它以关闭程序。它能为您提供帮助吗?我觉得我的电脑有一些特定的东西无法让我获得输入。
  • 删除更改显示模式的部分,是的,它对我来说很好;)
  • 谢谢你,它对我有用,但你知道用窗口而不是 JFrame 对象来做到这一点吗? (只是出于好奇)如果没有带有窗口对象的解决方案,我将使用它。
  • JWindow 是一种好奇心,据我记得,它实际上并不是可聚焦的,至少从键盘的角度来看,这可能解释了您的部分问题。关于 FSCM,不应该有任何视觉差异,如果您担心使其与 BufferedStategy 一起使用,您可以使用 Canvas 并将其添加到框架中
【解决方案2】:

我认为按键的默认事件处理是您只能从可聚焦的组件(即文本字段)中获取它们。但是,引用此post,您可以尝试使用将自定义KeyEventDispatcher(我认为这是AWT 的底层事件处理)添加到KeyboardFocusManager

【讨论】:

  • 我还不能尝试这个,因为我在我的手机上,但它看起来很有希望!如果可行,我会通知您,再次感谢您的帮助!
  • 或者只使用key bindings API,因为它就是为它设计的:P
猜你喜欢
  • 2014-05-18
  • 2012-02-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多