我的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(); ???
答案 0 :(得分:2)
有一些古老的遗迹,没有好主意建造
覆盖public void paintComponent (Graphics g
)而不是public void paint(Graphics g)
for Swing JPanel
下一行应为super.paint()
/ super.paintComponent()
不要在Object
/ paint
内加载任何paintComponent
,也不要加载FileIO
(无论是否来自资源)准备{{1}等等...到局部变量
覆盖Image
的{{1}},否则绘画返回零维度
使用getPreferredSize
代替今日JPanel
代替Swing Timer
答案 1 :(得分: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);
}