Fügen Sie mehrere Polygon-Objekte im selben JPanel-Frame hinzu

Also habe ich eine DrawStar-Klasse, die mit Polygon einen Stern zeichnet:

public void paintComponent(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;
    int[] cX = new int[] {x, x+5, x+20, x+8, x+16, x, x-16, x-8, x-20, x-5, x};
    int[] cY = new int[] {y, y+14, y+14, y+22, y+39, y+29, y+39, y+22, y+14, y+14, y};
    Polygon pol = new Polygon(cX, cY, 11);
    g2.setColor(this.color);
    g2.draw(pol);
    g2.fillPolygon(pol);
}

Dann erstelle ich in meiner Hauptklasse einen JPanel-Rahmen, um die Sterne zu zeichnen:

    ...
    JFrame starsframe = new JFrame();
    starsframe.setTitle("Random stars...");
    starsframe.setSize(600, 400);
    starsframe.setLocationRelativeTo(null);
    starsframe.setVisible(true);
    starsframe.setResizable(false);
    starsframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    DrawStar star1 = new DrawStar(300, 200, CreateColor(color));
    starsframe.add(star1);
    DrawStar star2 = new DrawStar(400, 300, CreateColor(color));
    starsframe.add(star2);
    ...

Es funktioniert jedoch nur mit einem Stern. Wenn ich eine zweite hinzufüge (wie oben), wird keine gezeichnet (CreateColor ist eine Funktion, die ich für die Sternfarbe implementiere). Wie kann ich sie alle zusammen auf dem Rahmen hinzufügen? Und noch etwas: Selbst wenn ich die Hintergrundfarbe des Rahmens auf Schwarz stelle, wird er nach dem Zeichnen des Sterns grau.

Vielen Dank!

Antworten auf die Frage(1)

Ihre Antwort auf die Frage