我有两个扩展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课
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应该位于背景中,以Creature为中心
然后将WorldView添加到小程序,并将Creature添加到WorldView。
您将需要在WorldView上使用适当的布局管理器来获取所需的布局。
关于java - 并非所有的JComponent都被绘制,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22867454/