如何在 JFrame window 中获得可关闭的全屏?

How to get closeable full screen in a JFrame window?

我正在尝试在 java 中构建网络浏览器,我希望在用户按下 fullScr 按钮并退出全屏模式时全屏显示当按下 F11 键时。

这是我的代码的一部分(它扩展了 JFrame)

public Hello() {
    currentScene();
    setResizable(true);
    JPanel buttonPanel1 = new JPanel();
    backButton.setIcon(new ImageIcon(Hello.class.getResource("/rsz_left_custom.png")));
    buttonPanel1.add(backButton);
    forwardButton.setIcon(new ImageIcon(Hello.class.getResource("/1813406178.png"));
    buttonPanel1.add(forwardButton);
    buttonPanel1.add(locationTextField, BorderLayout.EAST);
    JPanel buttonPanel2 = new JPanel(new BorderLayout(5, 5));
    fullScr.setIcon(new ImageIcon(Hello.class.getResource("/rsz_gnome-view-fullscreensvg (1).png")));
    fullScr.setPreferredSize(new Dimension(40, 40));
    fullScr.setBorderPainted(false);
    fullScr.setBackground(Color.decode("#330300"));
    fullScr.setLocation(1050, 25);
    fullScr.setToolTipText("Go Huge");
    //enters full screen mode when button is clicked
    fullScr.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            buttonPanel.setVisible(false);
            try{
            setUndecorated(true);
            }
            catch(Exception e){
                System.out.println(e);
            }
        }
    });
    //exits full screen mode when F11 is pressed
    addKeyListener(new KeyAdapter() {
           public void keyPressed(KeyEvent ke) {  // handler
        if(ke.getKeyCode() == KeyEvent.VK_F11){
            buttonPanel.setVisible(true);
            setUndecorated(false);
        }
       }});
    fullScr.setEnabled(true);
    buttonPanel2.add(fullScr, BorderLayout.LINE_END);
    buttonPanel.setBackground(Color.decode("#330300"));
    buttonPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
    buttonPanel.add(buttonPanel1, BorderLayout.WEST);
    buttonPanel.add(buttonPanel2, BorderLayout.EAST);
    JPanel lblBar = new JPanel(new BorderLayout());
    lblBar.add(lblStatus, BorderLayout.CENTER);
    fPane.add(jfxPanel);
    fPane.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
    totalPane.add(buttonPanel, BorderLayout.NORTH);
    totalPane.add(fPane, BorderLayout.CENTER);
    setExtendedState(JFrame.MAXIMIZED_BOTH);
    getContentPane().add(totalPane);
    setPreferredSize(new Dimension(1024, 600));
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    pack();
}

但是当我编译它时,它给我这样的错误:

java.awt.IllegalComponentStateException: The frame is displayable.
BUILD SUCCESSFUL (total time: 30 seconds)

而且按F11也不退出全屏模式,我该怎么办?提前致谢。

您必须将关键侦听器添加到它应该侦听的组件

theComponent.addKeyListener(new KeyAdapter() { ....

这里解释异常:Exception in thread "AWT-EventQueue-0" java.awt.IllegalComponentStateException: The frame is displayable

此处描述了解决方法:Dynamically show and hide JFrame decorations