将图像置于面板中间

时间:2012-01-04 09:15:57

标签: java swing graphics

我将在Java中使用Graphics并在JPanel上创建一个圆圈。 如何在JPanel中圈出圆圈?

package exerciseninetwo;
import javax.swing.*;
import java.awt.*;
import java.awt.geom.Ellipse2D;    

public class ExerciseNineTwo extends JFrame
{
    public ExerciseNineTwo()
    {
        super("My Frame");
        setSize(500, 500);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        add(new CanvasPanel());

        setVisible(true);        
    }        

    public static void main(String[] args)
    {
        new ExerciseNineTwo();
    }
}
class CanvasPanel extends JPanel
{        
    CanvasPanel()
    {
        setSize(120, 120);            
        //setBackground(Color.cyan);
    }

    protected void paintComponent(Graphics g)
    {
        Graphics2D comp = (Graphics2D)g;
        Ellipse2D circle = new Ellipse2D.Float(200, 200, 200, 200);
        comp.draw(circle);

        comp.setColor(Color.cyan);
        comp.fillRect(0,0,500,500);

        comp.setClip(circle);
        comp.setColor(Color.magenta);
        comp.fillRect(0,0,500,500);           
    }
}

4 个答案:

答案 0 :(得分:5)

只需在面板中间绘制它。

float x = getWidth()/2 - ELLIPSE_WIDTH/2;
float y = getHeight()/2 - ELLIPSE_HEIGHT/2;
Ellipse2D circle = new Ellipse2D.Float(x, y, ELLIPSE_WIDTH, ELLIPSE_HEIGHT);

答案 1 :(得分:3)

获取面板对象并查询X和Y尺寸参数(或宽度和高度)。将每个除以2将给出框架的中心。使用结果作为X和Y坐标创建一个圆。

喜欢

float x = (width-width of oval) /2;
float y = (height-height of oval) /2;

现在在eclipse的构造函数中设置x和y

答案 2 :(得分:3)

使用面板的getWidth()/getHeight()

int x=(getWidth()-ovalWidth)/2;
int y=(getHeight()-ovalHeight)/2;

检查面板宽度是否大于椭圆宽度,与高度相同。

答案 3 :(得分:2)

您可以轻松获得面板的大小并相应地放置圆圈:

Dimension size = getSize();
Ellipse2D circle = new Ellipse2D.Float(
    (size.width - 200) / 2,       // -200 due to the width/height of the circle
    (size.height - 200) / 2, 
    200, 200);