代码之家  ›  专栏  ›  技术社区  ›  Docteur

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

  •  -1
  • Docteur  · 技术社区  · 8 年前

    我试图以这样一种方式绘制JLabel(或带有图像的JComponent),即它的位置是图像的中心,而不是左上角。

    我试过用 fillOval drawImage 无济于事。我有一个对象的模型,其位置为16x16,我希望精灵的范围从0x0到32x32,而不是16x16到48x48。

    在图像中恢复: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);
    }
    
    1 回复  |  直到 8 年前
        1
  •  0
  •   Docteur    8 年前

    我最终解决这个问题的方法是在setLocation方法中偏移位置。这不是最美丽的答案,但现在它会做的。

    @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。