Image JPanel未在JFrame中绘制
我对java相当陌生,决定制作一个2D游戏。我正在试着粉刷面板,但根本不起作用。我用JFrames做了同样的事情,它也能工作,但如果可能的话,我希望它能用JPanels工作。这里有一些代码 这是一个仅用于绘制地图的类。从枚举调用图像Image JPanel未在JFrame中绘制,image,graphics,jpanel,repaint,paintcomponent,Image,Graphics,Jpanel,Repaint,Paintcomponent,我对java相当陌生,决定制作一个2D游戏。我正在试着粉刷面板,但根本不起作用。我用JFrames做了同样的事情,它也能工作,但如果可能的话,我希望它能用JPanels工作。这里有一些代码 这是一个仅用于绘制地图的类。从枚举调用图像 //called in paint method for panel public void draw(Graphics2D g2){ sLevel1.setupRect(); for(int i = 0; i < 24; i++){
//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);
}
}
}
}
}
最后,它被添加到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();
}
我不知道你到底想做什么,为什么它不起作用。你有没有试过用调试器一步一步地调试它?你发现了什么?但这是我根据你提供的信息提出的建议 现在不要使用draw方法,如果您愿意,只需将其注释掉即可。相反,请在绘制方法中执行此操作: 如果你的填充矩形行得通,但是你的图像不行,你知道你的图像有问题,你可以继续修复它
这里的信息确实不多,但你的问题中也没有多少信息。如果我能准确地知道出了什么问题,我可以给出更好的回答。这根本不管用,没什么好继续的。我也有一个像你一样的问题,但没有人回答。
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();
}
public void paint( Graphics g ) {
super.paint( g );
// draw something simple here, just so you know it's getting called, like a filled Rect
g.setColor( Color.BLUE );
g.fillRect( 0, 0, 50, 50 );
// try drawing the image later, after you verify this is being called with your rect
// Graphics2D g2 = (Graphics2D)g;
// g2.drawImage( Toolkit.getDefaultToolkit().getImage(eBlocks.GRASS1.getPath()), e*20, i*20, null);
}