题目:
*12.10 (游戏:显示一个棋盘)
编写一个程序,显示一个棋盘,棋盘中的每一个白色格和黑色格都是将背景色设置为黑色或者白色的JButton。
因为Jbutton无法设置为纯黑色,所以只好用JLabel代替,以后如果找到解决方案再来填坑。
September 16,2019更新
找到为什么不能用JButton的原因了,苹果系统的JButton是上不了色的,Windows系统可以,所以只需要把代码中的JLabel改成JButton就可以了。
效果:
代码如下:
package Test;
import javax.swing.*;
import java.awt.*;
public class Exercise12_10 extends JFrame {
public Exercise12_10(){
setLayout(new GridLayout(8,8));
for (int i = 1; i <=8 ; i++) {
if (i % 2 != 0) {
for (int j = 0; j <8 ; j++) {
if (j % 2 == 0) {
JLabel label1 = new JLabel();
label1.setBackground(Color.white);
label1.setOpaque(true);
add(label1);
} else {
JLabel label2 = new JLabel();
label2.setBackground(Color.black);
label2.setOpaque(true);
add(label2);
}
}
} else {
for (int j = 0; j <8 ; j++) {
if (j % 2 == 0) {
JLabel label1 = new JLabel();
label1.setBackground(Color.black);
label1.setOpaque(true);
add(label1);
} else {
JLabel label2 = new JLabel();
label2.setBackground(Color.white);
label2.setOpaque(true);
add(label2);
}
}
}
}
}
public static void main(String[] args) {
Exercise12_10 frame=new Exercise12_10();
frame.setTitle("Exercise12_10");
frame.setSize(400,400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
思路讲解
利用奇偶行进行控制黑白开头
if (i % 2 != 0) {}
可以判断这行是奇数还是偶数。
for (int i = 1; i <=8 ; i++) {}
最外圈的循环控制输出的个数,共64个。