This is bothering me, my code works and runs but when I went to run it, it seems to be looping my for loops twice, can anyone help me with my logic? Thanks...
Calling setPreferredSize()
and pack()
will cause paintComponent()
to be called twice because the display needs to be redrawn for each call.
Try removing pack()
and move set size to the bottom, like this:-
public Main() {
Random g = new Random();
//setPreferredSize(...); // commented this line
for (int i = 0; i < radius.length; i++) {
radius[i] = g.nextInt(50) + 1;
xArray[i] = g.nextInt(250) + 1;
yArray[i] = g.nextInt(150) + 1;
}
}
public void paintComponent(Graphics page) {
...
}
public static void main(String[] args) {
JFrame frame = new JFrame("Circles");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200); // added this line
frame.getContentPane().add(new Main());
// frame.pack(); // commented this line
frame.setVisible(true);
}
This should work properly now.
for(int i = 0; i < radius.length; i++) { for (int j = 0; j < radius.length; j++) {
Most loops where you wish to compare every pairing of two elements together is instead written like this:
for(int i = 0; i < radius.length; i++) { for (int j = i; j < radius.length; j++) {
(Note the j = i
in the second loop.)
This also lets you remove the i != j
test. :)
EDIT: Oops; j = i
means you still need to i != j
test -- if you used j = i+1
then you can remove the i != j
test. Sigh. :)