15.3

 1 import java.awt.Color;
 2 import java.awt.Graphics;
 3 import java.awt.GridLayout;
 4 
 5 import javax.swing.JButton;
 6 import javax.swing.JFrame;
 7 import javax.swing.JPanel;
 8 
 9 public class Test_15 extends JFrame{
10     public Test_15(){
11 //        setLayout(new GridLayout(8,8,0,0));
12         add(new JP());
13     }
14     
15     
16     public static void main(String[] args) {
17         // TODO Auto-generated method stub
18         Test_15 t = new Test_15();
19         t.setTitle("test");
20         t.setSize(400,400);
21         t.setLocationRelativeTo(null);
22         t.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
23         t.setVisible(true);
24     }
25 
26 }
27 
28 class JP extends JPanel{
29     boolean filled = true;
30     
31     protected void paintComponent(Graphics g){
32         super.paintComponent(g);
33         double x= 0,y=0;
34         int width = getWidth();
35         int height = getHeight();
36         for(int i = 0; i < 8; i++)
37         {
38             for (int j =0; j < 8; j++)
39             {
40         if(filled == false)
41         {
42         g.drawRect((int)x, (int)y, width/8, height/8);
43         filled = true;
44         x = x + width/8;
45         }
46         else
47         {
48             g.fillRect((int)x, (int)y, width/8, height/8);
49             filled = false;
50             x = x + width/8;
51         }
52             }
53             y = y + height/8;
54             x = 0;
55              if (i % 2 == 0)
56                  filled = false; 
57                   else
58                       filled = true;            
59         }
60     }
61 }
Test_15.java

显示结果为:

原文地址:https://www.cnblogs.com/wanjiang/p/5618136.html