这个小程序,我用两个Class来编写。是为了使得代码更加清楚,增强其可读性。
AutoFrame这个类里只是一个窗口类,用来实现以基本窗口的显示。
AutoFrame Code:
1 import javax.swing.JFrame; 2 3 public class AutoFrame extends JFrame{ 4 5 /* Define the global variable */ 6 int WIDTH = 500, HEIGHT = 400; // define the initial size 7 int X = 0, Y = 0; // define the initial location 8 9 /* The constructor */ 10 public AutoFrame() { 11 // TODO Auto-generated constructor stub 12 } 13 14 /* Display the window function */ 15 public void showFrame() 16 { 17 this.setSize(WIDTH, HEIGHT); 18 this.setLocation(X, Y); 19 this.setTitle("MY AUTO WINDOW"); 20 21 this.setVisible(true); // set the window is visible 22 this.setDefaultCloseOperation(EXIT_ON_CLOSE); // set the window can close with close button 23 } 24 }
WindowAction这个类里则是真正的窗口动作类。
WindowAction类里调用了thread线程现实窗口的自动移动和自动改变大小动作。
WindowAction Code:
1 public class WindowAction extends Thread { 2 3 static AutoFrame af = new AutoFrame(); // Create a object of AutoFrame 4 private int TIMES = 100; // define a limit times for the cycle 5 6 public void run() { 7 int times = TIMES; // define the cycle times is TIMES 8 9 int x = af.X, y = af.Y, w = af.WIDTH, h = af.HEIGHT; // Save the old values 10 int i; 11 for (i = 0; i <= times; ++i) { // cycle to change location of the window 12 af.showFrame(); 13 af.setLocation(++af.X, ++af.Y); // reset location of the window 14 System.out.println("times = " + i + ":"); 15 try { 16 sleep(100); 17 System.out.println("The frist thread sleep one second...\n"); 18 } catch (InterruptedException e) { 19 // TODO Auto-generated catch block 20 e.printStackTrace(); 21 } 22 } 23 24 for (i = 0; i <= times; ++i) { // cycle to change location of the window 25 af.showFrame(); 26 af.setSize(--af.WIDTH, --af.HEIGHT); // reset size of the window 27 System.out.println("times = " + i + ":"); 28 try { 29 sleep(100); // sleep 0.1 second 30 System.out.println("The second thread sleep one second...\n"); 31 } catch (InterruptedException e) { 32 // TODO Auto-generated catch block 33 e.printStackTrace(); 34 } 35 } 36 } 37 38 public static void main(String[] args) { 39 new WindowAction().start(); // call the function who in thread to start the thread 40 } 41 }