eg : 实训时跟着敲的实例,没什么想说的,直接奉上代码
import javax.swing.*; import java.awt.*; public class EcDemo { public static void main(String[] args) { JFrame jf = new JFrame(); jf.setSize(1024, 768); jf.setTitle("月食"); jf.setVisible(true); MoonPanel mp = new MoonPanel(); jf.add(mp); Thread tad = new Thread(mp); tad.start(); } } class MoonPanel extends JPanel implements Runnable { int x = 810, y = 170; //定义会动的月亮的坐标 public void paint(Graphics g) { super.paint(g); this.setBackground(Color.black); /*画月亮*/ g.setColor(Color.white); g.fillOval(860, 120, 80, 80); g.setColor(Color.black); g.fillOval(x, y, 80, 80); /*画星星*/ for(int i=0;i<30;i++){ int x = (int)(Math.random()*1024); int y = (int)(Math.random()*768); g.setColor(Color.yellow); g.drawString("*",x,y); } } public void run() { while (true) { x++; y--; if (x > 1024 && y < 0) { x = 810; y = 170; } try { Thread.sleep(100);//线程睡眠 } catch (InterruptedException e) { e.printStackTrace(); } /*每过1毫秒重新调用paint方法*/ repaint(); } } }