用中心的 X、Y 坐标绘制 JLabel

Drawing a JLabel with X,Y coordinate of the center

我正在尝试绘制 JLabel(或带有图像的 JComponent),使其位置位于图像的中心,而不是 top-left 角。

我试过 fillOvaldrawImage 都没有用。我有一个位置为 16x16 的对象模型,我希望精灵从 0x0 跨越到 32x32,而不是 16x16 到 48x48。

在图像中恢复:getLocation() 应该给我模型的位置(即中心),当我尝试绘画时,它应该使用中心的 x、y 坐标进行绘画,而不是在左上角.

有什么想法吗?

我的一些代码: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);
}

我最终解决问题的方法是在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。