I'm begining with JFrame, I'm triying to make a StarField, for the moment I'm adding the Star JComponent to the Starfield JFrame:
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JComponent;
public class Star extends JComponent{
public int x;
public int y;
private final Color color = Color.YELLOW;
public Star(int x, int y) {
this.x = x;
this.y = y;
}
public void paintComponent(Graphics g) {
g.setColor(color);
g.fillOval(x, y, 8, 8);
}
}
and the StarField code:
import javax.swing.*;
public class StarField extends JFrame{
public int size = 400;
public Star[] stars = new Star[50];
public static void main(String[] args) {
StarField field = new StarField();
field.setVisible(true);
}
public StarField() {
this.setSize(size, size);
for (int i= 0; i< stars.length; i++) {
int x = (int)(Math.random()*size);
int y = (int)(Math.random()*size);
stars[i] = new Star(x,y);
this.add(stars[i]);
}
}
}
The problem it's thar it only print one star, I think it is the last one, the coords are working like they are supposed to do it, so I think the mistake is in the JComponent or JFrame implementation, I'm self-learning, so maybe my code isn't the correct way for using swing.
Thank you, and sorry for my english, I'd tried to write it the best I know.
LayoutManager. If I remember correctly the defaultLayoutisBorderLayoutwhich allows a total of 5 components at 5 different spots.this.add(stars[i]);overwrites every component previously added as you can only have one component at theBorderLayout.CENTER(which is default and therefore will magically appended to youraddcall, so that it actually isthis.add(stars[i], BorderLayout.CENTER);)getPreferredSize()method. This would be based on the parameter suggested in 2. This is used by layout managers to determine the size of the component.