生成黑白相间的网格(位运算)

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class MyFrame {
	private static final int ROW = 25;
	private static final int COL = 25;

	JPanel jp = new JPanel(new GridLayout(ROW, COL));
	JFrame frame = new JFrame("Test");
	JLabel jl[][] = new JLabel[ROW][COL];

	public MyFrame() {

		initJLabel();
		initJPanel();
		initFrame();

	}

	private void initJPanel() {
		int i, j;
		for (i = 0; i < ROW; ++i) {
			for (j = 0; j < COL; ++j) {
				jp.add(jl[i][j]);
			}
		}
	}

	private void initFrame() {
		frame.setLayout(new BorderLayout());
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 关闭就结束程序
		frame.setVisible(true);
		frame.setSize(800, 800);
		frame.setResizable(false); // 无法最大化
		frame.setLocationRelativeTo(null); // 居中显示
		frame.setFocusable(true);

		frame.add(jp);

	}

	private void initJLabel() {
		int i, j;
		for (i = 0; i < ROW; ++i) {
			for (j = 0; j < COL; ++j) {
				jl[i][j] = new JLabel();
				jl[i][j].setOpaque(true);
				if (((i + j) & 1) == 0) {
					jl[i][j].setBackground(Color.WHITE);
				} else {
					jl[i][j].setBackground(Color.BLACK);
				}
			}
		}
	}

}

 

你可能感兴趣的:(算法,java)