绘制组件不绘制椭圆

时间:2017-05-05 23:11:01

标签: java paintcomponent

好的,所以我目前正在为一个项目制作一个蛇和梯子游戏,我遇到了一个我以前从未面对过的问题。我有一个名为Player的课程,它将成为游戏板上的一个圆圈。

paintComponent方法应该不断打印为true,但不是

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

1 个答案:

答案 0 :(得分:0)

您不应该扩展JComponent来创建新组件,而是通过覆盖paintComponent(..)来自定义绘制过程。

如果要使用自定义绘制方案创建新组件,请使用JPanel并覆盖paint(..)方法。

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

更多信息here