如何在JFrame窗口中全屏关闭?

时间:2016-12-11 19:26:39

标签: java swing jframe keylistener

我正在尝试在java中构建一个Web浏览器,我希望在用户按下 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时,它不会退出全屏模式。我该怎么办?提前谢谢。

2 个答案:

答案 0 :(得分:1)

答案 1 :(得分:0)

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

Horizontal Scroll View