我对java还很陌生,并决定制作一个2D游戏。我正在尝试绘制面板,但它根本不起作用。我用 JFrames 做了同样类型的事情并且它有效,但如果可能的话,我想让它与 JPanels 一起工作。这是一些代码
这是一个仅用于绘制地图的类。从枚举中调用图像
//called in paint method for panel
public void draw(Graphics2D g2){
sLevel1.setupRect();
for(int i = 0; i < 24; i++){
for(int e = 0; i < 24; i++){
if(level1.worldDat[i][e] != 0){
int c = level1.worldDat[i][e];
if(i == 1){
g2.drawImage(Toolkit.getDefaultToolkit().getImage(eBlocks.GRASS1.getPath()), e*20, i*20, null);
}else if(i == 2){
g2.drawImage(Toolkit.getDefaultToolkit().getImage(eBlocks.GRASS2.getPath()), e*20, i*20, null);
}else if(i == 3){
g2.drawImage(Toolkit.getDefaultToolkit().getImage(eBlocks.GRASS3.getPath()), e*20, i*20, null);
}else if(i == 5){
g2.drawImage(Toolkit.getDefaultToolkit().getImage(eBlocks.BORDER.getPath()), e*20, i*20, null);
}else{
g2.drawImage(Toolkit.getDefaultToolkit().getImage(eBlocks.NULL.getPath()), e*20, i*20, null);
}
}
}
}
}
这是它在面板中调用的地方,
@Override
public void paintComponent(Graphics g){
Graphics2D g2 = (Graphics2D) g;
super.paintComponent(g2);
worldDraw.draw(g2);
}
最后这是在 JFrame 中添加的地方,并且计时器用于重绘
public mainGameFrame() {
super("Tile Game");
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 510, 525);
//i also tried add, didnt work either
setContentPane(gamePanel);
addKeyListener(this);
Timer time = new Timer(32, new ActionListener(){
public void actionPerformed(ActionEvent e){
repaint();
gamePanel.repaint();
}
});
time.start();
}