gpt4 book ai didi

Java - 将形状添加到框架

转载 作者:行者123 更新时间:2023-12-01 06:25:02 25 4
gpt4 key购买 nike

我创建了一个 JFrame,然后创建了一个 JPanel 并设置了参数。我有一个名为 boardSquares 的 JPanel,其中每个方 block 稍后都会被着色。

一旦我尝试将检查器添加到棋盘上,棋盘颜色就会重新排列。

我曾多次尝试解决此问题,但没有成功。我也确信有更好的方法来做到这一点。下面是一些代码。感谢所有帮助!

    public void paintComponent(Graphics g)
{
g.setColor(Color.BLUE);
g.fillOval(0, 0, 30, 30);
}

public static void checkerBoard()
{
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
boardSquares[i][j] = new JPanel();

if ((i + j) % 2 == 0)
{
boardSquares[i][j].setBackground(Color.BLACK);
}
else
{
boardSquares[i][j].setBackground(Color.WHITE);
}
frameOne.add(boardSquares[i][j]);
}
}
}

最佳答案

看这个例子https://www.javaworld.com/article/3014190/learn-java/checkers-anyone.html

我稍微升级了你的例子抱歉,我没有太多时间

import java.awt.*;
import javax.swing.*;
import javax.swing.border.Border;

import java.awt.Color;
import java.awt.Graphics;

public class Circle extends JPanel
{
public static JFrame frameOne = new JFrame("Frame 1");
public static Circle boardSquares[][] = new Circle[8][8];

public static void main(String[] args)
{
checkerBoard();
frameOne.setSize(new Dimension(400,400));
frameOne.getContentPane().setLayout(new GridLayout(8,8,0,0));
frameOne.setBackground(Color.BLACK);
frameOne.setVisible(true);
frameOne.setResizable(false);
frameOne.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

boardSquares[1][1].setChecker(true);
}

private Color c;
private boolean checker;

public Circle(int i, int j) {
super();
//setBorder(new Border());
//set
if ((i + j) % 2 == 0)
{
c = Color.DARK_GRAY;

}
else
{
c = Color.WHITE;
}
}

void setChecker(boolean ch) {
checker = ch;
}

public static void checkerBoard()
{
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
boardSquares[i][j] = new Circle(i, j);

frameOne.add(boardSquares[i][j]);
}
}
}

public void paintComponent(Graphics g)
{
g.setColor(c);
g.fillRect(0, 0, 40, 40);
if (checker) {
g.setColor(Color.BLUE);
g.fillOval(4, 4, 32, 32);
}
}

}

关于Java - 将形状添加到框架,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49801506/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com