在此Java游戏中,healthBar(实心矩形)不允许任何内容在它们之后呈现。但是,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);
}

最佳答案

public class HealthBar extends JComponent {吓我一跳
paintComponent(g); //maybe this.paintComponent(g);吓我一跳
g2.dispose(); //Double check if I need this here不,你不这样做,是造成问题的原因...


无需HealthBarJComponent扩展。实际上,可能会争辩说您应该使用定义了简单interface方法的render,并且每个实体都应实现该方法...

但是,问题的核心是在未创建的dispose上下文中调用Graphics

09-25 21:39