0

I am trying to slowly fill a power-up bar which is a single big white rectangle slowly being overlapped by a yellow rectangle. I initially created a white and yellow rectangle with the x of the yellow one constantly changing. I am subtracting my game score to add 1 to the rectangle each time my score goes up by 1. Unfortunately I am getting an NullPointerException error when I run the program. This is occurring at the yellowRectangle.setSize line.

public void powerUp(Graphics2D win) {
    win.setColor(Color.white);
    Rectangle whiteRectangle = new Rectangle(685, 500, 100, 25);



    Rectangle yellowRectangle = new Rectangle(685, 500, myX, 25);

    win.fill(whiteRectangle);
}
public void draw(Graphics2D win) {

    if (gameState == 1) {
        scoreBoard(win, score);

        if(myX <= 100 && myRocket.score > 1) {
            myX += myRocket.score - (myRocket.score - 1);
            yellowRectangle.setSize(myX, 25);
            win.setColor(Color.yellow);
            win.fill(yellowRectangle);
        }
        powerUp(win);
     }
}

1 Answers1

0
public class App extends JFrame {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new App().setVisible(true));
    }

    public App() {
        setLayout(new BorderLayout());
        add(new MainPanel(), BorderLayout.CENTER);
        setSize(540, 90);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

    private static class MainPanel extends JPanel implements Runnable {

        private final Rectangle bounds = new Rectangle(10, 10, 500, 30);
        private int completePercentage;

        public MainPanel() {
            setBackground(Color.black);
            startTimer();
        }

        private void startTimer() {
            Thread thread = new Thread(this);
            thread.setDaemon(true);
            thread.start();
        }

        @Override
        public void paint(Graphics g) {
            super.paint(g);

            Color color = g.getColor();
            g.setColor(Color.yellow);
            int width = bounds.width * completePercentage / 100;
            g.fillRect(bounds.x, bounds.y, width, bounds.height);
            g.setColor(Color.white);
            g.fillRect(bounds.x + width, bounds.y, bounds.width - width, bounds.height);
            g.setColor(color);
        }

        @Override
        public void run() {
            try {
                while (true) {
                    Thread.sleep(500);
                    completePercentage = completePercentage == 100 ? 0 : completePercentage + 1;
                    repaint();
                }
            } catch(InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}
Oleg Cherednik
  • 17,377
  • 4
  • 21
  • 35