Sprite継承クラスのドラック例を示しましたが、画像の回転など特殊操作をしないのであれば、
JCompnentをドラックすることで、比較的簡単に画像を移動する処理が可能です。
以下で、JLabelを移動することで、画像移動を行わせる例を示します。
方法は色々ありますが、JLabelの継承クラスにドラックを行わせる処理を示します。
矢印が、JLabelを継承したCursorLabelクラスです。これがドラックで移動できます。
このCursorLabelクラス自体にドラック処理を埋め込んでいる例です。
以下にこのソースを示します。
package testsprite;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class CursorLabel extends JLabel implements MouseListener, MouseMotionListener
{
int width = 64;
int height = 64;
Polygon shape;//Shapeインターフェイス実装
Paint paint = new Color(255, 0, 0, 200);//カーソル塗り潰し色
Point prevPt;//以前のマウス位置
Point prevLocation;//以前の自身(ラベル)の位置
public CursorLabel(){
this.setSize(new Dimension(width, height));
this.shape = new Polygon();//Shapeインターフェイス実装
shape.addPoint(1, 1);//矢印の図形を作る座標作成
shape.addPoint(52, 10);
shape.addPoint(36, 24);
shape.addPoint(61, 42);
shape.addPoint(42, 61);
shape.addPoint(24, 36);
shape.addPoint(10, 52);
shape.addPoint(0, 0);
this.addMouseListener(this);
this.addMouseMotionListener(this);
}
public void paintComponent(Graphics g){//描画すべきタイミングで、呼び出されるメソッド
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setPaint(paint);//塗りつぶしの情報設定
g2.fill(shape);//塗りつぶし
BasicStroke stroke = new BasicStroke(2.0f);//線幅を5.0
g2.setStroke(stroke);//線描画設定
g2.setPaint(Color.BLACK);//塗りつぶしの情報設定
g.drawPolygon(shape);
}
public void mouseClicked(MouseEvent e){
}
public void mouseEntered(MouseEvent e){
}
public void mouseExited(MouseEvent e){
}
public void mousePressed(MouseEvent e){
Point pt = e.getPoint();
//System.out.println(pt.x + "," + pt.y);
this.prevPt = pt;
prevLocation = this.getLocation();
}
public void mouseReleased(MouseEvent e){
Point pt = e.getPoint();
//System.out.println(pt.x + "," + pt.y);
Point newLocation = new Point(this.prevLocation);
newLocation.x += pt.x - this.prevPt.x;
newLocation.y += pt.y - this.prevPt.y;
this.setLocation(newLocation);
}
public void mouseDragged(MouseEvent e){
Point pt = e.getPoint();
//System.out.println(pt.x + "," + pt.y);
Point newLocation = new Point(this.prevLocation);
newLocation.x += pt.x - this.prevPt.x;
newLocation.y += pt.y - this.prevPt.y;
this.setLocation(newLocation);
this.prevLocation = newLocation;
}
public void mouseMoved(MouseEvent e){
}
}
class TestCursorLabelPanel extends JPanel
{
CursorLabel cursor1 = new CursorLabel();
CursorLabel cursor2 = new CursorLabel();
TestCursorLabelPanel(){
this.setPreferredSize(new Dimension(400, 200));
this.setLayout(null);
this.add(cursor1);//先に追加配置した方が前面になります。
this.cursor1.setLocation(0, 0);
this.add(cursor2);//後で追加配置した方が下になります。
this.cursor2.setLocation(200, 100);
}
}
class TestCursorLabelFrame extends JFrame
{
public TestCursorLabelFrame(){
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
this.setContentPane(new TestCursorLabelPanel());
}
public static void main(String[] args){
TestCursorLabelFrame f =new TestCursorLabelFrame();
f.pack();
f.setVisible(true);
}
}