我创建了一个扩展JLabel的类,用作我的对象在游戏的JPanel中移动。问题将JLabel类绘制到另一个JPanel类
import javax.swing.*;
public class Head extends JLabel {
int xpos;
int ypos;
int xvel;
int yvel;
ImageIcon chickie = new ImageIcon(
"C:\\Users\\jjpotter.MSDOM1\\Pictures\\clavalle.jpg");
JLabel myLabel = new JLabel(chickie);
public Head(int xpos, int ypos, int xvel, int yvel){
this.xpos = xpos;
this.ypos = ypos;
this.xvel = xvel;
this.yvel = yvel;
}
public void draw(){
myLabel.setLocation(xpos, ypos);
}
public double getXpos() {
return xpos;
}
public double getYpos() {
return ypos;
}
public int getXvel() {
return xvel;
}
public int getYvel() {
return yvel;
}
public void setPos(int x, int y){
xpos = x;
ypos = y;
}
}
我然后试图将它添加到我的JPanel。从这里我将随机增加它的x和y坐标以将其浮在屏幕上。我无法将它绘制到JPanel上。我知道我缺少一个关键概念,涉及在不同的面板上绘制组件。这里是我在我的GamePanel类
import java.awt.Dimension;
import java.util.Random;
import javax.swing.*;
public class GamePanel extends JPanel {
Random myRand = new Random();
Head head = new Head(20,20,0,0);
public GamePanel(){
this.setSize(new Dimension(640, 480));
this.add(head);
}
}
有关如何获得此添加到JPanel的任何建议?另外,这是一个很好的方式来让图片随机在屏幕上随意浮动游戏吗?
重新格式化的代码;如果不正确请回复。 – trashgod 2010-06-09 15:07:27