使用Graphics2D着色2个椭圆

时间:2015-10-23 13:09:44

标签: java swing graphics2d

我想使用Graphics2D在Java中使用Color 2 Ovals。 Oval1(point)绿色和椭圆2(point2)蓝色。问题是Oval2变成绿色而Oval1变成黑色。有人知道问题是什么吗?

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

这是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;
    }   
}

1 个答案:

答案 0 :(得分:5)

更改这些来电的顺序......

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

你应该在JPanel.paintComponent画画。