0

我的 JPanel 不会重绘,我正在使用线程从循环中调用重绘方法。我 100% 确定循环有效,但是在调用 repaint(); 时 什么都没发生

package jgame.org.game;

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;

import javax.swing.ImageIcon;
import javax.swing.JPanel;

@SuppressWarnings("serial")
public class GamePanel extends JPanel implements Runnable
{   
    @Override
    public void paint(Graphics g)
    {
        if (gameState == 0)
        {
            g.drawImage(new ImageIcon(System.getProperty("user.home")
                    + "/jGame/FruitSlayer/Sprites/splash.png").getImage(), 0,
                    0, null);
        } else
        {
            g.drawImage(new ImageIcon(System.getProperty("user.home")
                    + "/jGame/FruitSlayer/Sprites/white.png").getImage(), 0,
                    0, null);
        }
        System.out.println("REPAINT");
    }

    public int currentLoopTime, gameState;

    @Override
    public void run()
    {
        while (true)
        {
            if (gameState != 1)
            {
                currentLoopTime += 1;
                if (currentLoopTime == 2000)
                {
                    gameState = 1;
                }
            }
            repaint();
        }
    }
}

还有我的游戏课:

package jgame.org.game;

import java.awt.Dimension;

import javax.swing.JFrame;

@SuppressWarnings("serial")
public class Game extends JFrame
{
    public Dimension size = new Dimension(605, 625);

    public Game()
    {
        super("Fruit Slayer");
        setSize(size);
        setResizable(false);
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        setVisible(true);
        (new Thread(new GamePanel())).start();
        add(new GamePanel());
    }

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

}

REPAINT 不在控制台中打印,但是当我将它添加到循环中时,它可以完美运行。是什么导致它不调用paint(Graphics);即使我使用 repaint();???

4

2 回答 2

2

有一些古代遗迹,没有好主意建造

  • override public void paintComponent (Graphics g) 而不是public void paint(Graphics g)Swing JPanel

  • 下一行应该是super.paint()/super.paintComponent()

  • 不要在/中加载任何Objects ,也不要(无论是否来自资源) prepare等...到局部变量paintpaintComponentFileIOImage

  • 覆盖getPreferredSizefor JPanel,否则绘画返回零维度

  • 用于Swing Timer今天Java6/7而不是Runnable#Thread

于 2013-10-18T21:31:36.320 回答
0

尝试这个

public Game()
{
    super("Fruit Slayer");
    setSize(size);
    setResizable(false);
    setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    setVisible(true);
    GamePanel panel = new GamePanel();
    (new Thread(panel)).start();
    setContentPane(panel);
}
于 2013-10-18T21:12:08.450 回答