Drawing: centering objects of different size

自古美人都是妖i 提交于 2019-12-11 22:19:56

问题


This program draws two circles of the inputted size on a jPanel, one on top of another. The problem is, the two circles are not centered. How can i solve this?

Code:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {  

jPanel.Repaint();
try{
    jLabel6.setText("");
    int a=Integer.parseInt(jTextField1.getText()); 

    Graphics2D gfx=(Graphics2D)jPanel1.getGraphics();
    gfx.clearRect(0, 0, getWidth(), getHeight()); 

    gfx.setColor(Color.red);
    gfx.fillOval(100,50,a,a);
    gfx.fillOval(100,50,a,a);

}catch(NumberFormatException e){
    jLabel6.setText("Incorrect data");
}
}

Result:


回答1:


The problem is, the two circles are not centered.

You have to understand that how x, y coordinate works in Swing custom drawing to position the component.

Try to understand the below screenshot.


Add width / 2 in the original x to get the centered x coordinate based on oval's width.

Do the same for height as well.

Sample code:

    int x = 50;
    int y = 50;
    int size = 100;

    g.setColor(Color.red);
    g.fillOval(x, y, size, size);

    int center = x + size / 2;
    size = 70;
    g.setColor(Color.blue);
    g.fillOval(center - size / 2, center - size / 2, size, size);




回答2:


Solved:

I used: gfx.fillOval(400-(a/2),50-(a/2),a,a);, and adjusted the x,y coordinates, to generate the circles on the desired position.



来源:https://stackoverflow.com/questions/23714810/drawing-centering-objects-of-different-size

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!