I would like to have a JLabel changint color to a random one, while jumping to a random position, and while changing its text.
but the setText and setBounds seem to clash and i don't know why. if you comment out the setText then the setBounds will work, but they won't work together.
import java.awt.*;
import java.util.*;
import javax.swing.*;
public class test2 extends JFrame {
private static JLabel label = new JLabel("0");
private static Random gen = new Random();
public test2() {
JPanel panel = new JPanel();
panel.add(label);
this.add(panel);
}
public static void move() {
for (int i = 0; i < 10; i++) {
int n = gen.nextInt(254)+1;
int nn = gen.nextInt(254)+1;
int nnn = gen.nextInt(254)+1;
label.setText(""+i);
//the setBounds command will not work with the setText command. why?
label.setBounds(n*2, nn*2, 20, 20);
label.setForeground(new Color(n, nn, nnn));
try {
Thread.sleep(200);
} catch (Exception e) {}
}
}
public static void main(String[] args) {
test2 frame = new test2();
frame.setVisible(true);
frame.setSize(600, 600);
frame.setResizable(true);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
move();
}
}
Don't know why it's happening, but here's an ugly work-around:
}
setBounds shouldn't work with a non-null layout, and your problem is happening because changing the text in the JLabel stimulates a re-layout of the JPanel, and since JPanels by default use FlowLayout, the JLabel stays at the top in the middle. So if you really need this functionality, then consider setting the layout of the JPanel to null, or else use a JLayeredPane.
Also you shouldn't be calling Thread.sleep(...) on the EDT, the Swing thread. Instead consider using a Swing Timer.
Since I disagreed with the other example, I will post an example of what I was recommending in its place, one that uses a Swing Timer: