My overriden paint method is not getting called

前提是你 提交于 2019-12-01 14:40:06

Do not override the paint method in Swing.

Override paintComponent instead.

Then you don't have to call paint or repaint for your subcomponents - this will be done automatically.

Alright guys, thanks for your help, in the end it required a combination of all your solutions to get it to work, what surprised me most was that it needed to be a JComponent for it to repaint properly. Here's the code that works

package base;

import java.awt.Color;
import java.awt.Graphics;
import javax.swing.BoxLayout;
import javax.swing.JComponent;
import javax.swing.JPanel;

public class HUD extends JPanel {

    private Shiphud[] shiphuds;

    public HUD(Ship[] ships) {
        shiphuds = new Shiphud[ships.length];
        this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
        for (int i = 0; i < shiphuds.length; i++) {
            shiphuds[i] = new Shiphud(ships[i]);
            this.add(shiphuds[i]);
        }
    }

    @Override
    public void paint(Graphics g) {
        super.paint(g);
        for (int i = 0; i < shiphuds.length; i++) {
            shiphuds[i].repaint();
        }
    }

    public void run() {
        repaint();
    }

    private class Shiphud extends JComponent {

        private Ship ship;

        public Shiphud(Ship ship) {
            this.ship = ship;
        }

        @Override
        public void paintComponent(Graphics g) {
            if (ship != null) {
                g.setColor(Color.BLACK);
                g.fillRect(0, 0, this.getWidth(), this.getHeight());
                int fullbar = (int) (this.getWidth() * 0.8);

                g.setColor(Color.GREEN);
                g.fillRoundRect(getWidth() / 10, getHeight() / 10,
                        (int) ((ship.energy / 1000) * fullbar), getHeight() / 6, 10, 10);

                g.setColor(Color.blue);
                g.fillRoundRect(getWidth() / 10, (int) (getHeight() * 0.4),
                        (int) ((ship.fuel / 1000) * fullbar), getHeight() / 6, 10, 10);

                g.setColor(Color.YELLOW);
                g.fillRoundRect(getWidth() / 10, (int) (getHeight() * 0.6),
                        (int) ((ship.ammo / 1000) * fullbar), getHeight() / 6, 10, 10);

                g.setColor(Color.MAGENTA);
                g.fillRoundRect(getWidth() / 10, (int) (getHeight() * 0.8),
                        (int) ((ship.special / 1000) * fullbar), getHeight() / 6, 10, 10);

            }
        }
    }
}

Cheers dudes!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!