我创建了一个扩展 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 的任何建议?另外,这是让游戏画面随机漂浮在屏幕上的好方法吗?