JFrame背景在开始后消失

时间:2014-11-25 15:21:06

标签: java swing jframe paint

所以我不确定问题出在哪里我用

设置Jframe背景
frame.getContentPane().setBackground(Color.green);

但是,一旦程序启动它会显示一个绿色闪烁然后它就消失了。

Game.java

package com.questkings.game;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.Timer;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Game extends JPanel{

Player player = new Player(this);

public Game(){
    addKeyListener(new KeyListener(){

        @Override
        public void keyTyped(KeyEvent e){
        }

        @Override
        public void keyReleased(KeyEvent e){
            player.keyReleased(e);
        }

        @Override
        public void keyPressed(KeyEvent e){
            player.keyPressed(e);
        }
    });
    setFocusable(true);
}

public void move(){
    player.move();
}

@Override
public void paint(Graphics g){
    super.paint(g);
    Graphics2D g2d = (Graphics2D) g;
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
            RenderingHints.VALUE_ANTIALIAS_ON);

    player.paint(g2d);
}

public void timer1() throws InterruptedException{
     int delay = 1000; //milliseconds
      ActionListener taskPerformer = new ActionListener() {
          public void actionPerformed(ActionEvent evt) {
          }
      };
      new Timer(delay, taskPerformer).start();;

Thread.sleep(10);
}

public static void main(String args[]) throws InterruptedException, Exception{
    int Width = 800;
    int Height = 400;
    Game game = new Game();

    JFrame frame = new JFrame("quest Kings");
    frame.setSize(Width, Height);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setBackground(Color.green);
    frame.add(game);
    frame.setResizable(false);


    //What to do after the program starts
    while(true){
        game.move();
        game.repaint();
        game.timer1();
    }
}
}

2 个答案:

答案 0 :(得分:0)

你的while(true) {...}循环块主线程,这就是发生这种情况的原因。尝试使用worker在单独的线程中执行此类操作。

此链接可能会有所帮助:

SWING WORKER EXAMPLE

答案 1 :(得分:0)

我会给你一个建议,直接从内容窗格中设置应用程序的颜色 ,就像这样

contentPane.setBackground(Color.red);