You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JFrame中获取输入映射与动作映射并实现按键全屏功能?

在JFrame中实现按键绑定触发全屏功能

JFrame作为顶层容器,本身并非JComponent的子类,所以确实没有getInputMap()和getActionMap()方法(你提到的getActionKey()应该是笔误,正确方法是getActionMap())。不过可以通过JFrame内部的组件来实现按键绑定,这是比Key Listener更可靠的方案。

替代方案:利用JFrame的内容面板/根面板实现按键绑定

Swing的按键绑定机制依赖JComponent,你可以直接使用JFrame的**内容面板(ContentPane)或者根面板(RootPane)**来设置绑定,这两个组件都属于JComponent,支持InputMap和ActionMap。

推荐使用WHEN_IN_FOCUSED_WINDOW作为输入映射的条件,这样无论窗口内哪个组件获得焦点,按键都会触发动作,更适合全局全屏需求。

代码示例

以下是绑定F11键切换全屏的完整示例:

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

public class FullScreenDemo extends JFrame {
    public FullScreenDemo() {
        setTitle("全屏演示");
        setSize(800, 600);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        // 获取内容面板(JComponent子类)
        JPanel contentPane = (JPanel) getContentPane();

        // 1. 设置输入映射:绑定F11键
        InputMap inputMap = contentPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
        inputMap.put(KeyStroke.getKeyStroke("F11"), "toggleFullScreen");

        // 2. 设置动作映射:关联触发的动作
        ActionMap actionMap = contentPane.getActionMap();
        actionMap.put("toggleFullScreen", new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                toggleFullScreen();
            }
        });
    }

    private void toggleFullScreen() {
        GraphicsDevice device = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
        if (device.isFullScreenSupported()) {
            // 切换全屏状态
            setUndecorated(!isUndecorated());
            device.setFullScreenWindow(isUndecorated() ? this : null);
        } else {
            JOptionPane.showMessageDialog(this, "当前设备不支持全屏模式");
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new FullScreenDemo().setVisible(true));
    }
}

关于Key Listeners的选择

不推荐使用Key Listeners实现这个需求,原因有两点:

  • 焦点限制:Key Listener只有在监听的组件获得焦点时才会响应按键,如果窗口内有多个可聚焦组件(比如文本框、按钮),可能出现按键不触发的情况。
  • 耦合性高:Key Listener需要直接处理按键事件,将按键逻辑和动作逻辑绑定在一起,不如按键绑定的解耦设计清晰,也不符合Swing的最佳实践。

内容的提问来源于stack exchange,提问作者FireGoose's Empire

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 05:52:36