【发布时间】:2014-04-04 15:52:08
【问题描述】:
我有两个扩展 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);
}
}
【问题讨论】:
-
你的班级已经是
JApplet,为什么还要创建一个新的JApplet? -
是的,至少可以说是一团糟,现在已经清理了@peeskillet,但仍然是同样的问题
-
1) 为了尽快获得更好的帮助,请发布MCVE(最小完整且可验证的示例)。 2) 为什么要编写小程序?如果是由于规范。老师请发给Why CS teachers should stop teaching Java applets。 3) 小程序不应尝试设置自己的大小。