如何解决 VK_ 问题和 NullPointerException?

发布于 2024-10-15 17:13:16 字数 10489 浏览 5 评论 0原文

import java.awt.Color;

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

/**
 *
 * @author Zeveso
 */
public class gameStart extends JFrame {

//set Global variables
final int WIDTH = 400, HEIGHT = 400;
//Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
double cOspeed = .5; //car 1 speed
double cTspeed = .5; //car 2 speed
Boolean winnerChosen = false;
Boolean canLap = false;
Boolean canLapT = false;
int cOlaps = 0;
int cTlaps = 0;
final int UP = 0, RIGHT = 1, DOWN = 2, LEFT = 3;
//direction of carOne
int cODirection = UP;
int cTDirection = UP;
//setup for double buffer
BufferedImage bufImg;
//set Global Track
//set outside
Rectangle left = new Rectangle(0, 0, WIDTH / 10, HEIGHT);
Rectangle right = new Rectangle((WIDTH / 10) * 9, 0, WIDTH / 5, HEIGHT);
Rectangle top = new Rectangle(0, 0, WIDTH, HEIGHT / 8);
Rectangle bottom = new Rectangle(0, (HEIGHT / 15) * 14, WIDTH, HEIGHT / 9);
//set inside
Rectangle topInr = new Rectangle((WIDTH / 11) * 2, (HEIGHT / 16) * 3, (WIDTH / 14) * 9, HEIGHT / 10);
Rectangle bottomInr = new Rectangle((WIDTH / 11) * 2, (HEIGHT / 16) * 12, (WIDTH / 14) * 9, HEIGHT / 10);
Rectangle leftInr = new Rectangle((WIDTH / 11) * 2, HEIGHT / 5, WIDTH / 5, (HEIGHT / 10) * 6);
Rectangle rightInr = new Rectangle((WIDTH / 12) * 6, (HEIGHT / 20) * 7, WIDTH / 2, (HEIGHT / 10) * 3);
//create finishLine
Rectangle finishLine = new Rectangle(WIDTH / 10, (HEIGHT / 10) * 8, WIDTH / 10, HEIGHT / 70);
//create checkpoint
Rectangle checkPoint = new Rectangle((WIDTH / 25) * 9, (HEIGHT / 10) * 5, WIDTH / 7, HEIGHT / 70);
//set Global Cars
Rectangle carOne = new Rectangle(WIDTH / 8, HEIGHT / 2, WIDTH / 30, WIDTH / 30);
Rectangle carTwo = new Rectangle(WIDTH / 9, HEIGHT / 2, WIDTH / 30, WIDTH / 30);

public gameStart() {
    super("Racing Game"); //set title
    setSize(400, 400); //set the size
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //make sure it closes when you click the exit button
    setVisible(true); //make sure its visible
    setResizable(false);
    setLocationRelativeTo(null); //set location of JFrame to middle
    /*
     * Set the location
     * First get the size of screen from Global variables
     * Then use .setLocation(); with those variables
     */

    //start double buffer
    bufImg = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration().createCompatibleImage(WIDTH, HEIGHT);

    //start cars up
    moveMyCar moveCar = new moveMyCar();
    moveMyCar2 moveCar2 = new moveMyCar2();
    moveCar.start();
    moveCar2.start();
}

@Override
public void paint(Graphics g) {
    Graphics2D gd = bufImg.createGraphics();
    try {
        //setup double buffer in paint
        gd.clearRect(0, 0, WIDTH, HEIGHT);
        //draw finishline
        gd.setColor(Color.RED); //set color
        gd.fillRect(finishLine.x, finishLine.y, finishLine.width, finishLine.height);
        //draw checkpoint
        //gd.setColor(Color.CYAN); //set color
        //gd.fillRect(checkPoint.x, checkPoint.y, checkPoint.width, checkPoint.height);
        //draw track
        //draw outside
        gd.setColor(Color.LIGHT_GRAY); //set color
        gd.fillRect(left.x, left.y, left.width, left.height);
        gd.fillRect(right.x, right.y, right.width, right.height);
        gd.fillRect(top.x, top.y, top.width, top.height);
        gd.fillRect(bottom.x, bottom.y, bottom.width, bottom.height);
        //draw inside
        gd.fillRect(topInr.x, topInr.y, topInr.width, topInr.height);
        gd.fillRect(bottomInr.x, bottomInr.y, bottomInr.width, bottomInr.height);
        gd.fillRect(leftInr.x, leftInr.y, leftInr.width, leftInr.height);
        gd.fillRect(rightInr.x, rightInr.y, rightInr.width, rightInr.height);

        //draw car1
        gd.setColor(Color.GREEN); // set color
        //gd.fillRect(carOne.x, carOne.y, carOne.width, carOne.height);
        gd.draw(carOne);
        //draw car2
        gd.setColor(Color.PINK);
        //gd.fillRect(carTwo.x, carTwo.y, carTwo.width, carTwo.height);
        gd.draw(carTwo);
    } finally {
        gd.dispose();
    }

    g.drawImage(bufImg, 0, 0, this);
}

@Override
public void update(Graphics g) {
    paint(g);
}

private class moveMyCar extends Thread implements KeyListener {
    @Override
    public void run() {
        addKeyListener(this);
        while (true) {
            try {
                repaint();

                //check for collisions
                if (carOne.intersects(left) || carOne.intersects(right) || carOne.intersects(top) || carOne.intersects(bottom) || carOne.intersects(topInr) || carOne.intersects(bottomInr) || carOne.intersects(leftInr) || carOne.intersects(rightInr)) {
                    if (cOspeed > 3.5) {
                        cOspeed = -5;
                    }
                    if (0 < cOspeed && cOspeed < 3.5) {
                        cOspeed = 1;
                    }
                }

                // check for laps
                if (carOne.intersects(finishLine) && cODirection == UP && canLap == true) {
                    cOlaps++;
                    canLap = false;
                }
                if (carOne.intersects(checkPoint) && cODirection == DOWN) {
                    canLap = true;
                }

                // see if player won
                if (cOlaps >= 3) {
                    winnerChosen = true;
                    JOptionPane.showMessageDialog(null, "Player 1 won the game!");
                    break;
                }
                if (winnerChosen) {
                    break;
                }

                //increase speed
                if (cOspeed <= 5) {
                    cOspeed += .2;
                }

                //change direction
                if (cODirection == UP) {
                    carOne.y -= cOspeed;
                }
                if (cODirection == DOWN) {
                    carOne.y += cOspeed;
                }
                if (cODirection == LEFT) {
                    carOne.x -= cOspeed;
                }
                if (cODirection == RIGHT) {
                    carOne.x += cOspeed;
                }

                Thread.sleep(100);

            } catch (Exception e) {
                System.out.println("Error: " + e);
                break;
            }
        }
    }

    public void keyPressed(KeyEvent event) {
        if (event.getKeyChar() == ' ') {
            if (cOspeed > -3) {
                cOspeed -= 1;
            }
        }
        System.out.println(event);
    }

    public void keyReleased(KeyEvent event) {
    }

    public void keyTyped(KeyEvent event) {
        if (event.getKeyChar() == 'a') {
            cODirection = LEFT;
        }
        if (event.getKeyChar() == 's') {
            cODirection = DOWN;
        }
        if (event.getKeyChar() == 'd') {
            cODirection = RIGHT;
        }
        if (event.getKeyChar() == 'w') {
            cODirection = UP;
        }
    }
}

private class moveMyCar2 extends Thread implements KeyListener {

    @Override
    public void run() {
        addKeyListener(this);
        while (true) {
            try {
                repaint();

                //check for collisions
                if (carTwo.intersects(left) || carTwo.intersects(right) || carTwo.intersects(top) || carTwo.intersects(bottom) || carTwo.intersects(topInr) || carTwo.intersects(bottomInr) || carTwo.intersects(leftInr) || carTwo.intersects(rightInr)) {
                    if (cTspeed > 3.5) {
                        cTspeed = -5;
                    }
                    if (0 < cTspeed && cTspeed < 3.5) {
                        cTspeed = 1;
                    }
                }

                // check for laps
                if (carTwo.intersects(finishLine) && cTDirection == UP && canLapT == true) {
                    cTlaps++;
                    canLapT = false;
                }
                if (carTwo.intersects(checkPoint) && cTDirection == DOWN) {
                    canLapT = true;
                }

                // see if player won
                if (cTlaps >= 3) {
                    winnerChosen = true;
                    JOptionPane.showMessageDialog(null, "Player 2 won the game!");
                    break;
                }
                if (winnerChosen) {
                    break;
                }

                //increase speed
                if (cTspeed <= 5) {
                    cTspeed += .2;
                }

                //change direction
                if (cTDirection == UP) {
                    carTwo.y -= cTspeed;
                }
                if (cTDirection == DOWN) {
                    carTwo.y += cTspeed;
                }
                if (cTDirection == LEFT) {
                    carTwo.x -= cTspeed;
                }
                if (cTDirection == RIGHT) {
                    carTwo.x += cTspeed;
                }

                Thread.sleep(100);

            } catch (Exception e) {
                System.out.println("Error: " + e);
                break;
            }
        }
    }

    public void keyPressed(KeyEvent event) {
        if (event.getKeyChar() == 'm') {
            if (cTspeed > -3) {
                cTspeed -= 1;
            }
        }
    }

    public void keyReleased(KeyEvent event) {
        System.out.println(event.getKeyCode());
    }

    public void keyTyped(KeyEvent event) {

        if (event.getKeyCode() == event.VK_LEFT) {
            cTDirection = LEFT;
        }
        if (event.getKeyCode() == event.VK_DOWN) {
            cTDirection = DOWN;
        }
        if (event.getKeyCode() == event.VK_RIGHT) {
            cTDirection = RIGHT;
        }
        if (event.getKeyCode() == event.VK_UP) {
            cTDirection = UP;
        }
      }
   }
}

这是我的代码。我想知道两件事。首先,我在第 80 行收到错误。 第 80 行:

Graphics2D gd = bufImg.createGraphics();

无论如何,它是线程“AWT-EventQueue-0”java.lang.NullPointerException 中的异常,我想知道我是否应该得到它。它不会每次都会发生,但有时会发生。如果没有,那么我该如何解决它?

我还使用 event.VK_ 键作为上、下、左、右箭头键,但它不起作用。它说“访问静态字段”。对此我该怎么办?

谢谢!

import java.awt.Color;

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

/**
 *
 * @author Zeveso
 */
public class gameStart extends JFrame {

//set Global variables
final int WIDTH = 400, HEIGHT = 400;
//Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
double cOspeed = .5; //car 1 speed
double cTspeed = .5; //car 2 speed
Boolean winnerChosen = false;
Boolean canLap = false;
Boolean canLapT = false;
int cOlaps = 0;
int cTlaps = 0;
final int UP = 0, RIGHT = 1, DOWN = 2, LEFT = 3;
//direction of carOne
int cODirection = UP;
int cTDirection = UP;
//setup for double buffer
BufferedImage bufImg;
//set Global Track
//set outside
Rectangle left = new Rectangle(0, 0, WIDTH / 10, HEIGHT);
Rectangle right = new Rectangle((WIDTH / 10) * 9, 0, WIDTH / 5, HEIGHT);
Rectangle top = new Rectangle(0, 0, WIDTH, HEIGHT / 8);
Rectangle bottom = new Rectangle(0, (HEIGHT / 15) * 14, WIDTH, HEIGHT / 9);
//set inside
Rectangle topInr = new Rectangle((WIDTH / 11) * 2, (HEIGHT / 16) * 3, (WIDTH / 14) * 9, HEIGHT / 10);
Rectangle bottomInr = new Rectangle((WIDTH / 11) * 2, (HEIGHT / 16) * 12, (WIDTH / 14) * 9, HEIGHT / 10);
Rectangle leftInr = new Rectangle((WIDTH / 11) * 2, HEIGHT / 5, WIDTH / 5, (HEIGHT / 10) * 6);
Rectangle rightInr = new Rectangle((WIDTH / 12) * 6, (HEIGHT / 20) * 7, WIDTH / 2, (HEIGHT / 10) * 3);
//create finishLine
Rectangle finishLine = new Rectangle(WIDTH / 10, (HEIGHT / 10) * 8, WIDTH / 10, HEIGHT / 70);
//create checkpoint
Rectangle checkPoint = new Rectangle((WIDTH / 25) * 9, (HEIGHT / 10) * 5, WIDTH / 7, HEIGHT / 70);
//set Global Cars
Rectangle carOne = new Rectangle(WIDTH / 8, HEIGHT / 2, WIDTH / 30, WIDTH / 30);
Rectangle carTwo = new Rectangle(WIDTH / 9, HEIGHT / 2, WIDTH / 30, WIDTH / 30);

public gameStart() {
    super("Racing Game"); //set title
    setSize(400, 400); //set the size
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //make sure it closes when you click the exit button
    setVisible(true); //make sure its visible
    setResizable(false);
    setLocationRelativeTo(null); //set location of JFrame to middle
    /*
     * Set the location
     * First get the size of screen from Global variables
     * Then use .setLocation(); with those variables
     */

    //start double buffer
    bufImg = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration().createCompatibleImage(WIDTH, HEIGHT);

    //start cars up
    moveMyCar moveCar = new moveMyCar();
    moveMyCar2 moveCar2 = new moveMyCar2();
    moveCar.start();
    moveCar2.start();
}

@Override
public void paint(Graphics g) {
    Graphics2D gd = bufImg.createGraphics();
    try {
        //setup double buffer in paint
        gd.clearRect(0, 0, WIDTH, HEIGHT);
        //draw finishline
        gd.setColor(Color.RED); //set color
        gd.fillRect(finishLine.x, finishLine.y, finishLine.width, finishLine.height);
        //draw checkpoint
        //gd.setColor(Color.CYAN); //set color
        //gd.fillRect(checkPoint.x, checkPoint.y, checkPoint.width, checkPoint.height);
        //draw track
        //draw outside
        gd.setColor(Color.LIGHT_GRAY); //set color
        gd.fillRect(left.x, left.y, left.width, left.height);
        gd.fillRect(right.x, right.y, right.width, right.height);
        gd.fillRect(top.x, top.y, top.width, top.height);
        gd.fillRect(bottom.x, bottom.y, bottom.width, bottom.height);
        //draw inside
        gd.fillRect(topInr.x, topInr.y, topInr.width, topInr.height);
        gd.fillRect(bottomInr.x, bottomInr.y, bottomInr.width, bottomInr.height);
        gd.fillRect(leftInr.x, leftInr.y, leftInr.width, leftInr.height);
        gd.fillRect(rightInr.x, rightInr.y, rightInr.width, rightInr.height);

        //draw car1
        gd.setColor(Color.GREEN); // set color
        //gd.fillRect(carOne.x, carOne.y, carOne.width, carOne.height);
        gd.draw(carOne);
        //draw car2
        gd.setColor(Color.PINK);
        //gd.fillRect(carTwo.x, carTwo.y, carTwo.width, carTwo.height);
        gd.draw(carTwo);
    } finally {
        gd.dispose();
    }

    g.drawImage(bufImg, 0, 0, this);
}

@Override
public void update(Graphics g) {
    paint(g);
}

private class moveMyCar extends Thread implements KeyListener {
    @Override
    public void run() {
        addKeyListener(this);
        while (true) {
            try {
                repaint();

                //check for collisions
                if (carOne.intersects(left) || carOne.intersects(right) || carOne.intersects(top) || carOne.intersects(bottom) || carOne.intersects(topInr) || carOne.intersects(bottomInr) || carOne.intersects(leftInr) || carOne.intersects(rightInr)) {
                    if (cOspeed > 3.5) {
                        cOspeed = -5;
                    }
                    if (0 < cOspeed && cOspeed < 3.5) {
                        cOspeed = 1;
                    }
                }

                // check for laps
                if (carOne.intersects(finishLine) && cODirection == UP && canLap == true) {
                    cOlaps++;
                    canLap = false;
                }
                if (carOne.intersects(checkPoint) && cODirection == DOWN) {
                    canLap = true;
                }

                // see if player won
                if (cOlaps >= 3) {
                    winnerChosen = true;
                    JOptionPane.showMessageDialog(null, "Player 1 won the game!");
                    break;
                }
                if (winnerChosen) {
                    break;
                }

                //increase speed
                if (cOspeed <= 5) {
                    cOspeed += .2;
                }

                //change direction
                if (cODirection == UP) {
                    carOne.y -= cOspeed;
                }
                if (cODirection == DOWN) {
                    carOne.y += cOspeed;
                }
                if (cODirection == LEFT) {
                    carOne.x -= cOspeed;
                }
                if (cODirection == RIGHT) {
                    carOne.x += cOspeed;
                }

                Thread.sleep(100);

            } catch (Exception e) {
                System.out.println("Error: " + e);
                break;
            }
        }
    }

    public void keyPressed(KeyEvent event) {
        if (event.getKeyChar() == ' ') {
            if (cOspeed > -3) {
                cOspeed -= 1;
            }
        }
        System.out.println(event);
    }

    public void keyReleased(KeyEvent event) {
    }

    public void keyTyped(KeyEvent event) {
        if (event.getKeyChar() == 'a') {
            cODirection = LEFT;
        }
        if (event.getKeyChar() == 's') {
            cODirection = DOWN;
        }
        if (event.getKeyChar() == 'd') {
            cODirection = RIGHT;
        }
        if (event.getKeyChar() == 'w') {
            cODirection = UP;
        }
    }
}

private class moveMyCar2 extends Thread implements KeyListener {

    @Override
    public void run() {
        addKeyListener(this);
        while (true) {
            try {
                repaint();

                //check for collisions
                if (carTwo.intersects(left) || carTwo.intersects(right) || carTwo.intersects(top) || carTwo.intersects(bottom) || carTwo.intersects(topInr) || carTwo.intersects(bottomInr) || carTwo.intersects(leftInr) || carTwo.intersects(rightInr)) {
                    if (cTspeed > 3.5) {
                        cTspeed = -5;
                    }
                    if (0 < cTspeed && cTspeed < 3.5) {
                        cTspeed = 1;
                    }
                }

                // check for laps
                if (carTwo.intersects(finishLine) && cTDirection == UP && canLapT == true) {
                    cTlaps++;
                    canLapT = false;
                }
                if (carTwo.intersects(checkPoint) && cTDirection == DOWN) {
                    canLapT = true;
                }

                // see if player won
                if (cTlaps >= 3) {
                    winnerChosen = true;
                    JOptionPane.showMessageDialog(null, "Player 2 won the game!");
                    break;
                }
                if (winnerChosen) {
                    break;
                }

                //increase speed
                if (cTspeed <= 5) {
                    cTspeed += .2;
                }

                //change direction
                if (cTDirection == UP) {
                    carTwo.y -= cTspeed;
                }
                if (cTDirection == DOWN) {
                    carTwo.y += cTspeed;
                }
                if (cTDirection == LEFT) {
                    carTwo.x -= cTspeed;
                }
                if (cTDirection == RIGHT) {
                    carTwo.x += cTspeed;
                }

                Thread.sleep(100);

            } catch (Exception e) {
                System.out.println("Error: " + e);
                break;
            }
        }
    }

    public void keyPressed(KeyEvent event) {
        if (event.getKeyChar() == 'm') {
            if (cTspeed > -3) {
                cTspeed -= 1;
            }
        }
    }

    public void keyReleased(KeyEvent event) {
        System.out.println(event.getKeyCode());
    }

    public void keyTyped(KeyEvent event) {

        if (event.getKeyCode() == event.VK_LEFT) {
            cTDirection = LEFT;
        }
        if (event.getKeyCode() == event.VK_DOWN) {
            cTDirection = DOWN;
        }
        if (event.getKeyCode() == event.VK_RIGHT) {
            cTDirection = RIGHT;
        }
        if (event.getKeyCode() == event.VK_UP) {
            cTDirection = UP;
        }
      }
   }
}

Here is my Code. I was wondering two things. First, I get an error on line 80.
Line 80:

Graphics2D gd = bufImg.createGraphics();

Anyways it is a Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException and I was wondering if I was suppose to get that. It does not happen every time, but it does sometimes. If not, then how would I go about fixing it?

Also I used the event.VK_ keys for Up, Down, Left, Right arrow keys and it is not working. It says "accessing static field". What should I do about that?

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

一桥轻雨一伞开 2024-10-22 17:13:16

我会在 BufferedImage 中进行背景绘制,然后在 JPanel 的 PaintComponent 中绘制 BufferedImage。您可以在此处了解如何执行此类操作:在 Swing 中绘画

例如,使用您已经创建的代码:

import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.*;

public class GameStartJPanel extends JPanel {
    private final static int WIDTH = 400, HEIGHT = 400;

    private final static Rectangle left = new Rectangle(0, 0, WIDTH / 10, HEIGHT);
    private final static Rectangle right = new Rectangle((WIDTH / 10) * 9, 0, WIDTH / 5, HEIGHT);
    private final static Rectangle top = new Rectangle(0, 0, WIDTH, HEIGHT / 8);
    private final static Rectangle bottom = new Rectangle(0, (HEIGHT / 15) * 14, WIDTH, HEIGHT / 9);

    private final static Rectangle topInr = new Rectangle((WIDTH / 11) * 2, (HEIGHT / 16) * 3, (WIDTH / 14) * 9,
                HEIGHT / 10);
    private final static Rectangle bottomInr = new Rectangle((WIDTH / 11) * 2, (HEIGHT / 16) * 12, (WIDTH / 14) * 9,
                HEIGHT / 10);
    private final static Rectangle leftInr = new Rectangle((WIDTH / 11) * 2, HEIGHT / 5, WIDTH / 5, (HEIGHT / 10) * 6);
    private final static Rectangle rightInr = new Rectangle((WIDTH / 12) * 6, (HEIGHT / 20) * 7, WIDTH / 2,
                (HEIGHT / 10) * 3);
    private final static Rectangle finishLine = new Rectangle(WIDTH / 10, (HEIGHT / 10) * 8, WIDTH / 10, HEIGHT / 70);

    private final static Rectangle checkPoint = new Rectangle((WIDTH / 25) * 9, (HEIGHT / 10) * 5, WIDTH / 7, HEIGHT / 70);

    private final static Rectangle carOne = new Rectangle(WIDTH / 8, HEIGHT / 2, WIDTH / 30, WIDTH / 30);
    private final static Rectangle carTwo = new Rectangle(WIDTH / 9, HEIGHT / 2, WIDTH / 30, WIDTH / 30);

    private BufferedImage backgroundImage;

    public GameStartJPanel() {
        backgroundImage = createBackgroundImage();
        setPreferredSize(new Dimension(WIDTH, HEIGHT));
    }

    private BufferedImage createBackgroundImage() {
        BufferedImage bckgdImage = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        Graphics2D gd = bckgdImage.createGraphics();
        try {

            gd.clearRect(0, 0, WIDTH, HEIGHT);

            gd.setColor(Color.RED);
            gd.fillRect(finishLine.x, finishLine.y, finishLine.width, finishLine.height);

            gd.setColor(Color.LIGHT_GRAY);
            gd.fillRect(left.x, left.y, left.width, left.height);
            gd.fillRect(right.x, right.y, right.width, right.height);
            gd.fillRect(top.x, top.y, top.width, top.height);
            gd.fillRect(bottom.x, bottom.y, bottom.width, bottom.height);

            gd.fillRect(topInr.x, topInr.y, topInr.width, topInr.height);
            gd.fillRect(bottomInr.x, bottomInr.y, bottomInr.width, bottomInr.height);
            gd.fillRect(leftInr.x, leftInr.y, leftInr.width, leftInr.height);
            gd.fillRect(rightInr.x, rightInr.y, rightInr.width, rightInr.height);

            // do this in the paintComponent method
            // gd.setColor(Color.GREEN);
            // gd.draw(carOne);
            // gd.setColor(Color.PINK);
            // gd.draw(carTwo);
        } finally {
            gd.dispose();
        }

        return bckgdImage;
    }

   @Override
   protected void paintComponent(Graphics g) {
      super.paintComponent(g);
      if (backgroundImage != null) {
          g.drawImage(backgroundImage, 0, 0, null);
      }

      Graphics2D g2 = (Graphics2D) g;
      g.setColor(Color.GREEN);
      g2.draw(carOne);
      g.setColor(Color.PINK);
      g2.draw(carTwo);
   }

    private static void createAndShowUI() {
        JFrame frame = new JFrame("GameStartJPanel");
        frame.getContentPane().add(new GameStartJPanel());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                createAndShowUI();
            }
        });
    }
}

I would do my background painting in a BufferedImage and then draw the BufferedImage in the paintComponent of a JPanel. You can learn about how to do something like this here: painting in Swing

For example, using your already created code:

import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.*;

public class GameStartJPanel extends JPanel {
    private final static int WIDTH = 400, HEIGHT = 400;

    private final static Rectangle left = new Rectangle(0, 0, WIDTH / 10, HEIGHT);
    private final static Rectangle right = new Rectangle((WIDTH / 10) * 9, 0, WIDTH / 5, HEIGHT);
    private final static Rectangle top = new Rectangle(0, 0, WIDTH, HEIGHT / 8);
    private final static Rectangle bottom = new Rectangle(0, (HEIGHT / 15) * 14, WIDTH, HEIGHT / 9);

    private final static Rectangle topInr = new Rectangle((WIDTH / 11) * 2, (HEIGHT / 16) * 3, (WIDTH / 14) * 9,
                HEIGHT / 10);
    private final static Rectangle bottomInr = new Rectangle((WIDTH / 11) * 2, (HEIGHT / 16) * 12, (WIDTH / 14) * 9,
                HEIGHT / 10);
    private final static Rectangle leftInr = new Rectangle((WIDTH / 11) * 2, HEIGHT / 5, WIDTH / 5, (HEIGHT / 10) * 6);
    private final static Rectangle rightInr = new Rectangle((WIDTH / 12) * 6, (HEIGHT / 20) * 7, WIDTH / 2,
                (HEIGHT / 10) * 3);
    private final static Rectangle finishLine = new Rectangle(WIDTH / 10, (HEIGHT / 10) * 8, WIDTH / 10, HEIGHT / 70);

    private final static Rectangle checkPoint = new Rectangle((WIDTH / 25) * 9, (HEIGHT / 10) * 5, WIDTH / 7, HEIGHT / 70);

    private final static Rectangle carOne = new Rectangle(WIDTH / 8, HEIGHT / 2, WIDTH / 30, WIDTH / 30);
    private final static Rectangle carTwo = new Rectangle(WIDTH / 9, HEIGHT / 2, WIDTH / 30, WIDTH / 30);

    private BufferedImage backgroundImage;

    public GameStartJPanel() {
        backgroundImage = createBackgroundImage();
        setPreferredSize(new Dimension(WIDTH, HEIGHT));
    }

    private BufferedImage createBackgroundImage() {
        BufferedImage bckgdImage = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        Graphics2D gd = bckgdImage.createGraphics();
        try {

            gd.clearRect(0, 0, WIDTH, HEIGHT);

            gd.setColor(Color.RED);
            gd.fillRect(finishLine.x, finishLine.y, finishLine.width, finishLine.height);

            gd.setColor(Color.LIGHT_GRAY);
            gd.fillRect(left.x, left.y, left.width, left.height);
            gd.fillRect(right.x, right.y, right.width, right.height);
            gd.fillRect(top.x, top.y, top.width, top.height);
            gd.fillRect(bottom.x, bottom.y, bottom.width, bottom.height);

            gd.fillRect(topInr.x, topInr.y, topInr.width, topInr.height);
            gd.fillRect(bottomInr.x, bottomInr.y, bottomInr.width, bottomInr.height);
            gd.fillRect(leftInr.x, leftInr.y, leftInr.width, leftInr.height);
            gd.fillRect(rightInr.x, rightInr.y, rightInr.width, rightInr.height);

            // do this in the paintComponent method
            // gd.setColor(Color.GREEN);
            // gd.draw(carOne);
            // gd.setColor(Color.PINK);
            // gd.draw(carTwo);
        } finally {
            gd.dispose();
        }

        return bckgdImage;
    }

   @Override
   protected void paintComponent(Graphics g) {
      super.paintComponent(g);
      if (backgroundImage != null) {
          g.drawImage(backgroundImage, 0, 0, null);
      }

      Graphics2D g2 = (Graphics2D) g;
      g.setColor(Color.GREEN);
      g2.draw(carOne);
      g.setColor(Color.PINK);
      g2.draw(carTwo);
   }

    private static void createAndShowUI() {
        JFrame frame = new JFrame("GameStartJPanel");
        frame.getContentPane().add(new GameStartJPanel());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                createAndShowUI();
            }
        });
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文