在学习语言的过程中,我使用Java创建了一个连接4的游戏。
我做了一个连接4的小单元,它基本上是一个画布的延伸,我用蓝色或透明颜色绘制每个像素,如果它在圆盘的半径内。
我的代码遇到的问题是单元格没有立即绘制,我可以看到所有像素在大约6-7秒后逐个着色,形成我的单元格。
我想画一个这样的单元格,把它们放在网格布局中,形成我的connect 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();
}
}我希望在调用paint方法以将其放入GridLayout或任何LayoutManager中时,能够像在paint方法中一样绘制扩展画布。
发布于 2019-03-26 21:50:47
您必须有一些东西来告诉AWT需要重新绘制GUI。我不能告诉你在哪里做这件事,因为你只向我们展示了你的代码片段。
https://stackoverflow.com/questions/55358719
复制相似问题