重点代码: 调整黑白方格
if(i%2==0)
{
if(k%2==0)
j[i].setBackground(color[0]);
else
j[i].setBackground(color[1]);
add(j[i]);
}
else
{
if(k%2!=0)
j[i].setBackground(color[0]);
else
j[i].setBackground(color[1]);
add(j[i]);
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
public class demo extends JFrame
{
public demo()
{
setLayout(new GridLayout(5,6,0,0));//窗格
setVisible(true);
setTitle("网格布局");//窗口标题
setSize(600,500);//窗口大小
setLocationRelativeTo(null);//窗口默认在中间位置
setDefaultCloseOperation(EXIT_ON_CLOSE);
//super();
Color []color=new Color[2];
color[0]=new Color(0,0,0);
color[1]=new Color(255,255,255);
JButton []j=new JButton[30];
for(int i=1;i<=5;++i)
for(int k=1;k<=6;++k)
{
j[i]=new JButton();
if(i%2==0)
{
if(k%2==0)
j[i].setBackground(color[0]);
else
j[i].setBackground(color[1]);
add(j[i]);
}
else
{
if(k%2!=0)
j[i].setBackground(color[0]);
else
j[i].setBackground(color[1]);
add(j[i]);
}
}
}
public static void main(String[] args)
{
new demo();
}
}