Jpanel的背景是灰色的

时间:2016-08-01 14:34:21

标签: java jpanel

我试图用java创建一个游戏。 在第一次我做了一个Jpanel并制作了一个FPS计数器,背景是白色的。 在那之后,当我按下ESCAPE时,我试图做到这一点,Jpanel关闭,然后当你按空格时,我试图做到这一点,背景移动到绿色但是之后,当我试图开始,Jpanel移动到灰色背景,FPS计数器已经消失。

这是框架类

public class Frame extends JFrame{

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


public Frame(){
    new JFrame();


    this.setTitle("Tower Defence - By Sahar Haine");
    this.setDefaultCloseOperation(EXIT_ON_CLOSE);
    this.setExtendedState(MAXIMIZED_BOTH);
    this.setUndecorated(true);
    this.setResizable(false);
    this.setVisible(true);


    Screen screen = new Screen(this);
    this.add(screen);
}

这是屏幕类:

public class Screen extends JPanel implements Runnable{


Thread thread = new Thread(this);
Frame frame;

private int fps = 0;

public int scene;

public Boolean running = false;

public Screen(Frame frame){
    this.frame = frame; 


    this.frame.addKeyListener(new KeyHandller(this));

    thread.start();

}

@Override
public void paintComponent(Graphics g){
    g.clearRect(0, 0, this.frame.getWidth(), this.frame.getHeight());

    g.drawString(fps + "", 10, 10);


    if(scene == 0){
        g.setColor(Color.BLUE);

    }else{

    }
    g.setColor(Color.GREEN);

    g.fillRect(0, 0, this.frame.getWidth(), this.frame.getHeight());
}



public void run() {
    System.out.println("Success");

    long lastFrame = System.currentTimeMillis();
    int frames = 0;

    running = true;
    scene = 0;

    while(running){
        try {
            repaint();

            frames++;

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


            Thread.sleep(1);
        } catch (InterruptedException ex) {
            Logger.getLogger(Screen.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    System.exit(0);
}




public class KeyTyped{
    public void keyESC(){
       running = false;

}

    public void keySPACE() {
      scene = 1;
    }

这是关键的处理程序类:

public class KeyHandler implements KeyListener{

private Screen screen;
private Screen.KeyTyped keyTyped;


public KeyHandler(Screen screen){
    this.screen = screen;
    this.keyTyped = this.screen.new KeyTyped();

}



public void keyTyped(KeyEvent e) {

}


public void keyPressed(KeyEvent e) {
    int keyCode = e.getKeyCode();

    System.out.println(e.getKeyCode());

    if(keyCode == 27){
        this.keyTyped.keyESC();

    }

    if(keyCode == 27){
        this.keyTyped.keySPACE();

    }
}


public void keyReleased(KeyEvent e) {

}

2 个答案:

答案 0 :(得分:0)

立即跳出的一个问题是你有硬编码" keyCode = 27"对于Escape和Space都不正确。 " 27 - 逃脱"和" 32 - 空间"。请使用KeyEvent.VK_ESCAPE和KeyEvent.VK_SPACE,而不是硬编码值,KeyEvents

编辑1

还要确保在"填充"之后绘制字符串。或者"填充"将过度绘制FPS字符串,你将看不到它。

答案 1 :(得分:0)

我认为你必须打电话

 super.paintComponent(g)

作为paintComponent方法中的第一行覆盖。