下面是一个使用 JFrame 来绘制一个 5x5 大小的棋盘的示例代码:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ChessBoard extends JFrame {

    private JPanel boardPanel;
    private Cell[][] cells;

    public ChessBoard() {
        setTitle('Chess Board');
        setSize(600, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        boardPanel = new JPanel(new GridLayout(5, 5));
        boardPanel.setBackground(Color.WHITE);
        getContentPane().add(boardPanel, BorderLayout.CENTER);

        cells = new Cell[5][5];
        for (int i = 0; i < 5; i++) {
            for (int j = 0; j < 5; j++) {
                cells[i][j] = new Cell();
                boardPanel.add(cells[i][j]);
            }
        }
    }

    private class Cell extends JPanel {

        private boolean selected;

        public Cell() {
            setBackground(Color.YELLOW);
            setBorder(BorderFactory.createLineBorder(Color.BLACK));
            addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    selected = !selected;
                    setBackground(selected ? Color.RED : Color.YELLOW);
                }
            });
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            int width = getWidth();
            int height = getHeight();
            int size = Math.min(width, height) / 5;
            int x = (width - size) / 2;
            int y = (height - size) / 2;

            g.setColor(Color.BLUE);
            g.fillPolygon(new int[]{x + size / 2, x + size, x + size / 4, x + 3 * size / 4, x},
                    new int[]{y, y + size / 2, y + size, y + size, y + size / 2}, 5);
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new ChessBoard().setVisible(true);
            }
        });
    }
}

在这个示例代码中,我们创建了一个名为 ChessBoard 的 JFrame 子类。在构造方法中,我们设置了窗体的标题、大小、关闭操作和位置。然后,我们创建了一个名为 boardPanel 的 JPanel,使用 GridLayout 来布局。接下来,我们创建了一个名为 cells 的二维数组,用于存储棋盘上的每个格子。在每个格子的构造方法中,我们设置了背景色为黄色,并添加了一个鼠标点击事件监听器。在监听器中,我们通过切换 selected 变量的值来选中或取消选中格子,并根据选中状态设置背景色。在每个格子的 paintComponent 方法中,我们使用 Graphics 对象绘制了一个小的蓝色五角星。

最后,在 main 方法中,我们通过 SwingUtilities.invokeLater 方法来创建并显示 ChessBoard 窗体。

Java JFrame 棋盘绘制:点击选中格子变色

原文地址: https://www.cveoy.top/t/topic/pcHl 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录