So I have a DrawStar class that draws a star using Polygon like that:
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);
}
Then in my main class I create a JPanel frame to draw the stars:
...
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);
...
However, it only works with one star. If I add a second one (like above), none is drawn (CreateColor is a function I implement for the star color). How can I add them all along on the frame? And one more thing, even if I set the frame's background color to Black, it gets Gray after the star is drawn.
Thanks!
I reproduce your problem. It was
Layout
problem. By defaultJFrame
hasBorderLayout
withCENTER
alignment. You should change your layout and screen size.To see the two stars I used
GridLayout(1,2)
and biggersetSize(1000, 700)
. But it is not optimum solution. You should get thex
,y
dynamically with corresponding to Screen Size usinggetWidth()
andgetHeight()
method.