在这个java游戏中,healthBars(填充的矩形)不允许在它们之后渲染任何内容。但是,healthBarBorders需要出现在顶部,因为它们本质上是一个内部有alpha的框架,允许透视矩形。因为矩形来自Swing类而其他被渲染的东西都不是,所以这就是问题所在。任何解决方法?
public void render() {
Graphics g = bs.getDrawGraphics();
//RENDER HERE
backgroundImage.render(g);
player.render(g);
healthBars.render(g); //The rectangles (
healthBarBorders.render(g);
//END RENDER
g.dispose();
bs.show();
}
HealthBar类
public class HealthBar extends JComponent {
int healthP1;
int healthP2;
public void render(Graphics g) {
paintComponent(g); //maybe this.paintComponent(g);
}
//Constructor
public HealthBar(int healthP1, int healthP2) {
this.healthP1 = healthP1;
this.healthP2 = healthP2;
}
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
//Player 1 health bar
g2.setColor(Color.RED);
Rectangle redBarP1 = new Rectangle(10, 10, 300, 30);
g2.fill(redBarP1);
g2.setColor(Color.GREEN);
Rectangle greenBarP1 = new Rectangle(10, 10, healthP1, 30);
g2.fill(greenBarP1);
//Player 2 health bar
g2.setColor(Color.RED);
Rectangle redBarP2 = new Rectangle(800, 10, 300, 30);
g2.fill(redBarP2);
g2.setColor(Color.GREEN);
Rectangle greenBarP2 = new Rectangle(800, 10, healthP2, 30);
g2.fill(greenBarP2);
g2.dispose(); //Double check if I need this here
}
}
BackgroundImage渲染方法:
public void render(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
g2.drawImage(background, 0, -27, 1200, 600, null);
}
玩家渲染方法:
public void render(Graphics g) {
if(attack)
attackAnimation.render(g, x, y, 400 * Game.SCALE, 400* Game.SCALE);
else
g.drawImage(im.player, x, y, 400 * Game.SCALE, 400 * Game.SCALE, null);
}
HealthBarBorders渲染方法:
public void render(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
g2.drawImage(healthBorder1, 10, 10, 300, 30, null);
g2.drawImage(healthBorder2, 800, 10, 300, 30, null);
}
答案 0 :(得分:1)
public class HealthBar extends JComponent {
吓到我了...... paintComponent(g); //maybe this.paintComponent(g);
吓到我了...... g2.dispose(); //Double check if I need this here
不,你不是,是你问题的原因...... HealthBar
无法从JComponent
延伸。事实上可以说你应该使用interface
来定义一个简单的render
方法,你的每个实体都应该实现它......
但问题的核心是在您未创建的dispose
上下文中调用Graphics