本文介绍了绘图:不同大小的居中对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此程序在jPanel上绘制输入大小的两个圆圈,一个在另一个上方.问题是,两个圆没有居中.我该如何解决?

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?

代码:

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");
}
}

结果:

推荐答案

您必须了解x,y坐标在Swing自定义工程图中如何定位组件.

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

尝试了解以下屏幕截图.

Try to understand the below screenshot.

在原始的x中添加width / 2,以基于椭圆的宽度获得居中的x坐标.

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.

示例代码:

    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);

这篇关于绘图:不同大小的居中对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 03:25