我有两个对象扩展JComponent,这两个对象都覆盖了paintComponent()。当只有一个或另一个添加到Jpanel时,它被正确绘制,但是如果我添加两个,则只显示一个。
我添加两者的init方法如下:
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课程
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);
}
}
答案 0 :(得分:1)
顶级容器的默认布局是BorderLayout。默认情况下,如果未指定约束,则组件将添加到CENTER。但是,只有一个组件可以添加到CENTER中,因此只显示添加的最后一个组件。
WorldView应该位于前景中以Creature为中心的背景中
然后将WorldView添加到applet并将Creature添加到WorldView。
您需要在WorldView上使用适当的布局管理器来获得所需的布局。