Java矩形填充

时间:2019-01-21 05:22:53

标签: java

我正在尝试慢慢填充一个加电工具栏,这是一个大的白色矩形,逐渐被黄色矩形覆盖。我最初创建了一个白色和黄色的矩形,其中黄色的x不断变化。我要减去游戏分数,以便每次将分数上升1时都将矩形加1。不幸的是,运行程序时出现NullPointerException错误。这发生在yellowRectangle.setSize行。

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 个答案:

答案 0 :(得分: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();
            }
        }
    }

}