问题描述
我正在尝试编写一个破砖机项目的代码,但在图形方面遇到了问题。我不明白如何正确更新我的面板。当我调用 repaint() 方法时,它不会每次都更新。我的“修复”是在我的面板的 paintComponent() 方法中添加对 repaint() 的调用,但这似乎不对,我的面板将重绘多次。 这是我的代码:
public void play()
{
long framesDrawn = 0;
long lastFrame = System.currentTimeMillis();
long currentTime = System.currentTimeMillis();
while(!hasGameEnded())
{
double dt = (currentTime - lastFrame)/1000.;
if(dt > 1./_fps) // Draws a new frame at the desired fps
{
framesDrawn++;
System.out.println(dt);
moveItems(dt);
drawNewFrame();
System.out.println("new frame drawn (frame "+framesDrawn+" )\n");
lastFrame = currentTime;
}
currentTime = System.currentTimeMillis();
}
}
private void drawNewFrame()
{
ArrayList<GameItem> allItems = new ArrayList<>();
allItems.addAll(_allItems);
allItems.addAll(_platforms);
_gameFrame.getGamePanel().updateItems(allItems);
_gameFrame.getGamePanel().repaint();
_gameFrame.repaint();
}
我的自定义 JFrame 和 JPanel 是:
public class GameFrame extends JFrame {
private GamePanel _gamePanel;
public GameFrame(GamePanel gamePanel)
{
_gamePanel = gamePanel;
this.setTitle("Brickbreaker");
this.setSize(800,1200);
this.setLocationRelativeto(null);
this.setDefaultCloSEOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(true);
this.setContentPane(_gamePanel);
this.setVisible(true);
}
public GamePanel getGamePanel()
{
return _gamePanel;
}
}
public class GamePanel extends JComponent {
private int _gameWidth,_gameHeight;
private ArrayList<GameItem> _gameItems;
public GamePanel(int gameWidth,int gameHeight,ArrayList<GameItem> gameItems )
{
_gameWidth = gameWidth;
_gameHeight = gameHeight;
_gameItems = gameItems;
this.setopaque(true);
this.setBackground(Color.WHITE);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
int x = getX();
int y = getY();
int height = getHeight();
int width = getWidth();
float widthRatioMultiplier = ( (float)width )/( (float)_gameWidth );
float heightRatioMultiplier = ( (float) height)/( (float) _gameHeight);
for( GameItem gameItem : _gameItems)
{
gameItem.draw(g,widthRatioMultiplier,heightRatioMultiplier );
}
repaint();
}
public void updateItems(ArrayList<GameItem> updatedItems)
{
_gameItems = updatedItems;
}
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)