我創建了一個擴展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