Simple exercises with Swing

Keywords: Java

Title:

* 12.10 (Game: Show a chessboard)
Write a program to show a chessboard. Each white and black box in the chessboard sets the background color to black or white JButton.

Because Jbutton cannot be set to pure black, it has to be replaced by JLabel. If you find a solution later, fill the pit again.

Effect:

The code is as follows:

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);
    }
}

Train of thought

Using parity lines to control black-and-white beginnings

if (i % 2 != 0) {}

It can be judged whether the line is odd or even.

    for (int i = 1; i <=8 ; i++) {}

The number of output cycles in the outermost loop is 64.

Posted by Daleeburg on Mon, 07 Oct 2019 00:21:55 -0700