Search code examples
javaswinggraphics2d

Coloring 2 Ovals with Graphics2D


I want to Color 2 Ovals in Java with Graphics2D. Oval1(point) Green and Oval2(point2) Blue. The Problem is that Oval2 becomes green and Oval1 black. Does somebody knows what the problem is?

enter image description here left(oval1) right(oval2)

Here is the SSCCE:

GameView.java

import javax.swing.JFrame;
import stackoverflow.GameView;

public class GameView extends JFrame{
    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    private Game game = new Game();

    public GameView(){
        JFrame gameFrame = new JFrame("Game");
        gameFrame.setSize(500, 300);
        gameFrame.setVisible(true);
        gameFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        gameFrame.add(game);        
        game.runGame();
    }

    public static void main(String[] args) throws InterruptedException {
        new GameView();     
    }
}

Game.java

import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
import stackoverflow.Point;

public class Game extends JPanel{
    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    private Point point = new Point(Color.GREEN);
    private Point point2 = new Point(Color.BLUE);

    public void runGame(){
        repaint();
        point2.setX(300);
    }

    public void paint(Graphics g) {
        point.paint(g);
        point2.paint(g);
    }   
}

Point.java

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;

public class Point {

    private int x = 100;
    private int y = 100;
    private int width = 10;
    private int height = 10;

    private Color color;

    public Point(Color color){
        this.color = color;
    }

    public void paint(Graphics g) {
        Graphics2D g2d = (Graphics2D) g;    
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.fillOval(x, y, width, height);
        g2d.setColor(this.color);
    }

    public int getX() {
        return x;
    }

    public void setX(int x) {
        this.x = x;
    }

    public int getY() {
        return y;
    }

    public void setY(int y) {
        this.y = y;
    }   
}

Solution

  • Change the order of these calls...

    g2d.fillOval(x, y, width, height);
    g2d.setColor(this.color);
    

    And you should be painting in JPanel.paintComponent instead.