2016-10-21 6 views
-1

JLabel(またはイメージ付きのJComponent)を、その場所が左上隅ではなくイメージの中心になるように描画しようとしています。中心のX、Y座標を持つJLabelを描画

fillOvaldrawImageを使用してみました。私は16x16の位置を持つオブジェクトのモデルを持っており、スプライトが16x16から48x48ではなく、0x0から32x32に及ぶことを望みます。

イメージ内で再開されました。getLocation()はモデルの位置(つまり中心)を返します。ペイントしようとすると、左上隅ではなく中央のx、y座標で描画されます。

enter image description here

私のコードのいくつかのビット:JPanelの更新にスプライトを表示しようとしている:

@Override 
public void update(Observable o, Object arg) { //Is ran everytime WorldControler simulates a tick 
    this.removeAll(); 
    paintCreatures(arg); 
    this.revalidate(); 
    this.repaint(); 
} 

/** 
* 
* @param arg : The LinkedList that notifyObserver passes through in WorldControler 
*/ 
private void paintCreatures(Object arg){ 
    LinkedList<Creature> cList = (LinkedList<Creature>) arg; 
    for(Creature c : cList){ 
     ViewCreature vc = new ViewCreature(c,8); 
     this.add(vc); 
     vc.setVisible(true); 
     vc.setSize(8,8); 
     System.out.println(vc.getX() + " " + vc.getY()); 
    } 
} 

私は現在持っているpaintComponent:

@Override 
public void paintComponent(Graphics g){ 
    super.paintComponent(g); 
    Graphics2D g2d = (Graphics2D) g; 
    g2d.drawImage(img, this.getX()+size/2, this.getY()+size/2, null); 
} 
+0

私はlable内の画像ではなく、lableを配置することをお勧めします。これはFlowLayoutを使用して行うことができます。https://docs.oracle.com/javase/tutorial/uiswing/layout/flow.html –

+0

絶対位置で作業しているので(これは進化シミュレータなので、生き生きとした動きが期待されます)私は現在、 'setLayout(null)'を使っています。私が読んだことから、それはJPanel上で正確な位置を与える唯一の方法です。別の方法がありますか? – Docteur

+0

ですので、こちらをご覧ください:http://www.developer.com/java/other/article.php/893471/Fun-with-Java-Sprite-Animation-Part-1.htm –

答えて

0

私は最終的に解決方法問題は、setLocationメソッドのLocationをオフセットすることです。それは答えの中で最も美しいものではありませんが、今は仕事をするでしょう。

@Override 
public void setLocation(int x, int y) { 
    super.setLocation(x-(size/2), y-(size/2)); 
} 
@Override 
public void setLocation(Point p) { 
    super.setLocation((int)p.getX()-size/2,(int)p.getY()-size/2); 
} 

この回答を改善するためのご意見がありましたら、ご意見、ご回答をお願いします。 paintComponentをこれでオーバーライドする必要はありません。

関連する問題