import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Demo extends JPanel {
public static void main(String[] args) {
JFrame frame=new JFrame("满天星");
Demo demo=new Demo();
frame.setLayout(null);
frame.setSize(600,600);
frame.setLocation(50, 50);
frame.setLocationRelativeTo(null);
frame.setBackground(Color.BLUE);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
demo.setSize(500, 500);
demo.setLocation(20,30);
frame.add(demo);
frame.setVisible(true);
demo.go();
}
@Override
public void paint(Graphics g) {
setBackground(Color.BLACK);
Font font=new Font("宋体",Font.BOLD,20);
g.setFont(font);
g.setColor(Color.WHITE);
for(int i=0;i<50;i++){
Random random=new Random();
int x=random.nextInt(500);
int y=random.nextInt(500);
g.drawString("*", x, y);
}
}
public void go(){
Timer timer=new Timer();
timer.schedule(new TimerTask(){
public void run() {
repaint();
}
}, 500, 500);
}
}
为什么不是每次显示50个,而是每次添加50个,按照道理应该是每次显示50个覆盖掉前面的啊
求大虾指点
Java String
------解决方案--------------------
你了漏了一句super.paint(g);应该在paint(Graphics g)函数里加入super.paint(g)就可以了,而且一定要是第一句,如果不调用super.paint(g)时不会重画的,因为super.paint(g)中调用了其他控制面板的函数如update用于画出组件的背景色等