Java 画一个5X5的方形矩阵
效果图如下:
思路:创建一个窗口,使其居中于屏幕中央,使用drawRect(x, y, width, height)画正方形。
1 import java.awt.Graphics; 2 import java.awt.Insets; 3 import java.awt.Toolkit; 4 import java.awt.event.WindowAdapter; 5 import java.awt.event.WindowEvent; 6 7 import javax.swing.JFrame; 8 9 public class FiveXFive extends JFrame { 10 11 public static void main(String[] args) { 12 FiveXFive f = new FiveXFive(); 13 f.launchFrame(); 14 15 } 16 17 public void launchFrame() { 18 // The width & Height of the window 19 final int formWidth = 500; 20 final int formHeight = 500; 21 // The width & Height of the screen 22 int screenWidth = (int)Toolkit.getDefaultToolkit().getScreenSize().getWidth(); 23 int screenHeight = (int)Toolkit.getDefaultToolkit().getScreenSize().getHeight(); 24 25 // Set title, size, location & visible 26 this.setTitle("Hello World! I'm coming!"); 27 // width + left + right, height + top + bottom 28 this.setSize(formWidth+8+8, formHeight+31+8); 29 // set window in the middle 30 this.setLocation((screenWidth-formWidth)/2, (screenHeight-formHeight)/2); 31 this.setVisible(true); 32 33 Insets insets = this.getInsets(); 34 System.out.println("top: " + insets.top); 35 System.out.println("bottom: " + insets.bottom); 36 System.out.println("left: " + insets.left); 37 System.out.println("right: " + insets.right); 38 39 this.addWindowListener(new WindowAdapter() { 40 public void windowClosing(WindowEvent e) { 41 System.exit(0); 42 } 43 }); 44 } 45 46 public void paint(Graphics g) { 47 g.drawLine(8, 31, 508, 531); 48 g.drawLine(8, 531, 508, 31); 49 for (int y = 31; y < (500+31); y += 100) { 50 for (int x = 8; x < (500+8); x += 100) { 51 g.drawRect(x, y, 100, 100); 52 } 53 } 54 } 55 }