我正试图编码一个小的砖破坏者项目,我有一个图形方面的问题。我不知道如何正确更新我的面板。当我调用repaint()方法时,它不会每次都更新。我的“修复”是在我的面板的paintcomponent()方法中添加对repaint()的调用,但它似乎不正确,我的面板将多次重画。这是我的密码:
我有我的play()方法可以让游戏正常运行:
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();
}
}
它调用drawnewframe()方法:
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;
}
}
暂无答案!
目前还没有任何答案,快来回答吧!