使用KeyEventDispatcher设置jframe大小

时间:2013-04-24 20:03:01

标签: java swing size jframe keyevent

这是我的主要课程

package Apocalypse;

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

public class Main extends JFrame{
    private int xSize, ySize;

    public Main(){
        super("Zombie Apocalypse");
        Toolkit tk = Toolkit.getDefaultToolkit();
        xSize = (int) tk.getScreenSize().getWidth();
        ySize = (int) tk.getScreenSize().getHeight();
        setSize(xSize,ySize);
        setUndecorated(true);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        KeyboardFocusManager kfm = KeyboardFocusManager.getCurrentKeyboardFocusManager();
        kfm.addKeyEventDispatcher(new MyDispatcher());
        add(new Level1());
        setVisible(true);
    }

    public static void main(String[] args){
        new Main();
    }

    private class MyDispatcher implements KeyEventDispatcher{
        public boolean dispatchKeyEvent(KeyEvent e){
            if(e.getID() == KeyEvent.KEY_PRESSED){
                if(e.getKeyCode() == KeyEvent.VK_ESCAPE){
                    System.out.println("It Worked");
                    setUndecorated(false);
                }
            }
            return false;
        }
    }
}

正如您在我的KeyEventDispatcher类中看到的那样,我想将setUndecorated设置为false,以便您可以关闭游戏,但它不起作用。我该怎么做?

1 个答案:

答案 0 :(得分:2)

在显示框架后,您无法更改其装饰,因为setUndecorated()在这种情况下会抛出IllegalComponentStateException。要解决此问题,您可以创建新的装饰框架,将内容移动到它并处理旧框架。