如果我添加一个KeyListener,repaint()不起作用

时间:2017-09-23 12:30:47

标签: java keylistener repaint

所以我按照了一个youtube教程,教你如何用Java编写一个小游戏。即使我有与视频中的人完全相同的代码,我也有一点问题。

inliner index.html >index-backed.html
gzip -c index-backed.html >index.html.gz

问题是,只要我将KeyListener添加到框架中,就不会调用repaint()。如果删除KeyListener,它可以工作。我不认为问题是我的KeyHandler类,因为如果我使用标准的KeyListener,问题仍然存在。

1 个答案:

答案 0 :(得分:0)

很难在不知道游戏目的或使用的特定KeyHandler实现的情况下回答这个问题。以下对我有用:

public class Screen extends JPanel implements Runnable {
    Thread thread = new Thread(this);
    Frame frame;
    int fps = 0;
    int scene;
    boolean running = false;

    public Screen(Frame frame) {
        this.setFocusable(true);
        this.frame = frame;
        frame.setFocusable(true);
        frame.addKeyListener(new KeyListener() {

            @Override
            public void keyTyped(KeyEvent e) {}

            @Override
            public void keyPressed(KeyEvent e) {
                handleKeyChar(e.getKeyChar());
            }

            @Override
            public void keyReleased(KeyEvent e) {}

            private void handleKeyChar(char c) {
                switch (c) {
                case '0':
                    scene = 0;
                    break;
                case '1':
                    scene = 1;
                    break;
                default:
                    scene = 2;
                }
            }

        });
        thread.start();
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.clearRect(0, 0, this.frame.getWidth(), this.frame.getHeight());
        if (scene == 0) {
            g.setColor(Color.BLUE);
        } else if (scene == 1) {
            g.setColor(Color.GREEN);
        } else {
            g.setColor(Color.WHITE);
        }

        g.fillRect(0, 0, getWidth(), getHeight());
        g.setColor(Color.BLACK);
        g.drawString(fps + "", 20, 40);
    }

    public void run() {
        System.out.println("[Success] Frame Created!");
        long lastFrame = System.currentTimeMillis(); 
        int frames = 0;
        running = true;
        scene = 0;

        while (running) {
            repaint(); 
            frames++; 

            if (System.currentTimeMillis() - 1000 >= lastFrame) { 
                fps = frames;
                frames = 0;
                lastFrame = System.currentTimeMillis();
            }

            try {
                Thread.sleep(1); 
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }

        System.exit(0); 

    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("Example");
        frame.setSize(600, 600);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Screen panel = new Screen(frame);
        frame.add(panel);
        frame.setVisible(true);
    }
}