gpt4 book ai didi

java - 尝试制作棋盘格

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

我正在尝试根据我正在参加的计算机科学类(class)的模板制作一个棋盘。但是,当我运行它时,屏幕上没有任何显示。我猜我缺少一些代码来实际将正方形绘制到屏幕上,但我已经尝试了很多方法,但仍然一无所获。

   import java.applet.Applet;
import java.awt.*;
import java.util.Random;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;


public class Checkers extends JApplet
{
private final int MAX_SIZE = 8;
private final int APP_WIDTH = 400;
private final int APP_HEIGHT = 400;
private final int MAXSIZE = 8;


Square[][] sq;

public void paint(Graphics page)
{

setBackground(Color.white);
fillBoard(page); // draws the method that will draw the checkers
setSize (APP_WIDTH,APP_HEIGHT);

}

public void fillBoard(Graphics page)
{
sq = new Square[8][8];

int x,y;
Color rb;

for (int row = 0; row < MAXSIZE; row++)
for (int col = 0; col < MAXSIZE; col++)
{
x = row * (APP_WIDTH/MAXSIZE);
y = col * (APP_HEIGHT/MAXSIZE);
if ( (row % 2) == (col % 2) )
rb = Color.red;
else
rb = Color.blue;
sq[row][col] = new Square (x, y, rb);
}
}

class Square
{


private int x, y = 0;
private Color c;
private boolean occupied;
private Color checkerColor;


public Square (int x, int y, Color c)
{
this.x = x;
this.y = y;
this.c = c;
}

public void setX (int x)
{
x = this.x;
}

public int getX ()
{
return x;
}

public void setY (int y)
{
y= this.y;
}

public int getY ()
{
return y;
}

public void setColor (Color c)
{
c = this.c;
}

public Color getColor ()
{
return c;
}

public void setOccupy (boolean occupied)
{
occupied = this.occupied;
}

public boolean getOccupy ()
{
return occupied;
}

public void setCheckerColor (Color c)
{
checkerColor = this.checkerColor;
}

public Color getCheckerColor ()
{
return checkerColor;
}

public String toString()
{
return ("X coordinate: " + x + "\nY coordinate:" + y + "\nSquare color: " + c);
}


public void draw (Graphics page)
{
page.setColor(c);
page.fillRect(x, y, 50, 50);
}

最佳答案

你永远不会调用Square#draw

话虽如此,每次调用 paint 方法时,我都会对调用 fillBoard 持谨慎态度,事实上,我不鼓励您重写 paint 首先。

我可能要做的是检查 fillBoard 中的 sq 是否为 null,然后仅生成数组。回到绘制方法,我将简单地使用复合循环并绘制每个正方形。

您应该从 JPanel 之类的东西开始,并重写它的 paintComponent 方法,而不是重写 JAppletpaint ,请确保调用 super.paintComponent!

您应该这样做的原因有很多,但最主要的原因是 JApplet 不是双缓冲的,这意味着当绘图更新时您会看到“闪烁”。 JPanel 默认情况下是双缓冲的,为您节省了大量的工作和时间来实现您自己的解决方案...

完成此操作后,获取自定义面板并将其添加到小程序中。

我会把所有的绘画逻辑都移到它上面。看看Performing Custom Painting了解更多详情

关于java - 尝试制作棋盘格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21300960/

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