gpt4 book ai didi

java - 并非所有 JComponent 都被绘制

转载 作者:行者123 更新时间:2023-12-01 13:11:03 26 4
gpt4 key购买 nike

我有两个扩展 JComponent 的对象,这两个对象都重写 PaintComponent()。当仅将其中之一添加到 Jpanel 时,它会正确绘制,但是如果我添加两者,则仅显示一个。

添加两者的我的初始化方法如下:

public class Applet extends JApplet {

long time_interval = 200; // length of time between moves in ms
int w = 75;
int h = 75;
int[][] a = new int[w][h]; // creates a 2D array to use as background
Creature test;

public void init() {
System.out.println("Zachary Powell 1104583");
resize(750, 850);

WorldView tv = new WorldView(a);
// add(applet, BorderLayout.CENTER);

test = new Creature(100, 30, 1);
add(tv);
add(test);

startTimer();
}
...

但是电视没有绘制

我的生物类别:

public class Creature extends JComponent{
int health;
boolean dead;
int xpos, ypos;
static int size = 10;

Creature(int h, int y, int x) {
dead = false;
health = h;
ypos = y;
xpos = x;
}

void Update() {
checkHealth();
}

private void checkHealth() {
if (health <= 0)
dead = true;
}

public void reduceHealth(int amount) {
health -= amount;
}

public void move() {
if (xpos < 75) {
xpos++;
} else {
xpos = 1;
}
reduceHealth(1);
}

public void paintComponent(Graphics g) {
g.setColor(Color.BLUE);
g.fill3DRect(xpos * size, ypos * size, size, size, true);
}
}

还有我的 WorldView 类(class)

public class WorldView extends JComponent {
static Color[] colors =
{black, green, blue, red,
yellow, magenta, pink, cyan};
int[][] a;
int w, h;
static int size = 10;
//Create the object with the array give
public WorldView(int[][] a) {
this.a = a;
w = a.length;
h = a[0].length;
}

public void paintComponent(Graphics g) {
for (int i = 0; i < w; i++) {
for (int j = 0; j < h; j++) {
g.fill3DRect(i * size, j * size,
size, size, true);
}
}
}

public Dimension getPreferredSize() {
return new Dimension(w * size, h * size);
}
}

最佳答案

顶级容器的默认布局是 BorderLayout。默认情况下,如果您不指定约束,组件将添加到 CENTER。但是,只能将一个组件添加到 CENTER,因此仅显示最后添加的一个组件。

WorldView should be in the backround centred with Creature in the foreground

然后将 WorldView 添加到小程序中,并将 Creature 添加到 WorldView 中。

您需要在 WorldView 上使用适当的布局管理器来获得所需的布局。

关于java - 并非所有 JComponent 都被绘制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22867454/

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