有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java矩形填充

我试着慢慢地填充一个加电条,它是一个大的白色矩形,慢慢地被一个黄色矩形重叠。我最初创建了一个白色和黄色的矩形,其中黄色的x不断变化。每次我的分数上升1,我就减去我的游戏分数,在矩形上加1。不幸的是,当我运行程序时,我得到了一个NullPointerException错误。这发生在黄色矩形上。设置尺寸线

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

  1. # 1 楼答案

    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();
                }
            }
        }
    
    }