我在学习语言的过程中使用 Java 创建了一个连接 4 的游戏。
我做了一个连接 4 的小单元格,它基本上是画布的延伸,我用蓝色或透明颜色绘制每个像素(如果它在磁盘的半径内(。
我在代码中遇到的问题是单元格没有立即绘制,我可以看到所有像素在大约 6-7 秒后一一着色形成我的单元格。
我想画这样一个单元格来将它们放置在网格布局中并形成我的连接 4 网格。
我做错了什么?
试图在互联网上搜索解决方案,但到目前为止还没有找到。我不能使用 SWING。
package Puis4;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
public class Vue_Cellule_Grille extends Canvas {
// Attributs
int width;
int height;
// Constructeur
public Vue_Cellule_Grille() {
}
public Vue_Cellule_Grille(int width, int height) {
this.width = width;
this.height = height;
}
// Methodes
public void paint(Graphics g) {
// TODO : Afficher lorsque c'est peint.
int width = this.getWidth();
int height = this.getHeight();
int centreX = width/2;
int centreY = height/2;
Double diametre = this.getWidth() * 0.80;
Double rayon = diametre/2;
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
Double distance = Math.sqrt(Math.pow(centreX-i, 2.0) + Math.pow(centreY-j, 2.0));
if (distance > rayon) {
g.setColor(Color.BLUE);
} else {
// Le constructeur prends les valeurs RGB en float et pas en double.
g.setColor(new Color((float) 1.0,(float) 1.0, (float) 1.0, (float) 0.5));
}
g.fillRect(i, j, 1, 1);
}
}
}
}
package Puis4;
import java.awt.Frame;
import java.awt.LayoutManager;
public class Vue_Plateau extends Frame {
// Main de Test
public Vue_Plateau() {
super("Cellule Grille du Plateau");
this.setBounds(600, 600, 300, 300);
this.addWindowListener(new Controlleur_Fermer_Plateau(this));
// Layout & composants
Vue_Cellule_Grille v = new Vue_Cellule_Grille();
this.add(v);
this.setVisible(true);
}
}
package Puis4;
public class Test {
public static void main(String[] args) {
new Vue_Plateau();
}
}
我希望我的扩展画布在我调用它以将其放入 GridLayout 或任何布局管理器中时,立即像我在 paint 方法中所做的那样绘制。
你必须有一些东西告诉AWT需要重新绘制GUI。我无法告诉您在哪里执行此操作,因为您只向我们展示了您的代码片段。