importjava.awt.Canvas;
importjava.awt.Graphics;
importjavax.swing.JFrame;
publicclassICextendsCanvas{
privatestaticfinallongserialVersionUID=-2611185708860234130L;
publicvoidpaint(Graphicsg){
ints=50;//单元格大小
intc=0;//可取0或1以改变第一单元格是否填充
intrc=10;//行列数
for(inti=0;i<rc;i++){
c++;
if(rc%2>0)++c;
for(intj=0;j<rc;j++){
g.drawRect(i*s,j*s,s,s);
if(++c%2!=0)
g.fillRect(i*s,j*s,s,s);
}
}
g.dispose();
}
publicstaticvoidmain(String[]args){
JFramef=newJFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(600,600);
f.setLocationRelativeTo(null);
f.getContentPane().add(newIC());
f.setVisible(true);
}
}
上面是直接按你的要求在画布上打印的,下面是有组件排版的:
importjava.awt.Color;
importjavax.swing.*;
publicclassChessextendsJPanel{
privatestaticfinallongserialVersionUID=-5380742576273506004L;
//grids:行数和列数,gridsize:单元格的高和宽
publicChess(intgrids,intgridsize){
super(null);
for(inti=0;i<grids;i++){
for(intj=0;j<grids;j++){
JLabell=newJLabel();
l.setSize(gridsize,gridsize);
l.setLocation(i*gridsize+i,j*gridsize+j);
if((i+j)%2==0){
l.setBackground(Color.black);
l.setOpaque(true);
}
l.setBorder(BorderFactory.createLineBorder(Color.black));
add(l);
}
}
}
publicstaticvoidmain(String[]args){
JFramef=newJFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(620,645);
f.setLocationRelativeTo(null);
f.add(newChess(10,60));
f.setVisible(true);
}
}
注:这些已经很简单了,如果还看不懂,你回去再多补补基础吧!