简体   繁体   中英

Paint Component Not Drawing Oval

Ok so I'm currently making a snakes and ladders game for a project and I have encountered a problem in which I was never faced before with. I have a class called Player which would be a circle on the game board.

The paintComponent method should be printing true constantly however, it does not

public class Player extends JComponent {
    private double playerX;
    private double playerY;
    private double diameter;
    private String playerColor;
    HashMap<String, Color> colorMap = new HashMap();

    public Player(String playerColor, double playerX, double playerY, double diameter) {
        this.playerColor = playerColor;
        this.playerX = playerY;
        this.playerY = playerY;
        this.diameter = diameter;
        setSize(getPreferredSize());
        setLocation((int) diameter, (int) diameter);
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension((int) diameter * 2, (int) diameter * 2);
    }

    @Override
    public void paintComponent(Graphics g) {
        Graphics2D g2d = (Graphics2D) g;
        super.paintComponent(g2d);
        setDoubleBuffered(true);
        g2d.drawOval((int) playerX, (int) playerY, (int) diameter * 2, (int) diameter * 2);
        System.out.println(true);
    }
}

You should not extend JComponent to create a new component, but to customize the painting process by overriding paintComponent(..) .

If you want to create a new component with its custom painting scheme, use a JPanel and override the paint(..) method.

public class Player extends JPanel {

    private static final long serialVersionUID = 1L;

    private double playerX;
    private double playerY;
    private double diameter;
    private String playerColor;
    HashMap<String, Color> colorMap = new HashMap<>();

    public Player(String playerColor, double playerX, double playerY, double diameter) {
        this.playerColor = playerColor;
        this.playerX = playerY;
        this.playerY = playerY;
        this.diameter = diameter;
        setSize(getPreferredSize());
        setLocation((int) diameter, (int) diameter);
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension((int) diameter * 2, (int) diameter * 2);
    }

    @Override
    public void paint(Graphics g) {
        super.paint(g);
        Graphics2D g2d = (Graphics2D) g;
        setDoubleBuffered(true);
        g2d.drawOval((int) playerX, (int) playerY, (int) diameter * 2, (int) diameter * 2);
        System.out.println(true);
    }
}

More info here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM