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 に追加する方法について何か提案はありますか? また、これはゲームの画面の周りにランダムに画像を浮かせる良い方法ですか?