gpt4 book ai didi

java - 将图像置于面板中间

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:30:53 25 4
gpt4 key购买 nike

我开始掌握 Java 中的图形并在 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);
}
}

最佳答案

只需将其绘制在面板中间即可。

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

关于java - 将图像置于面板中间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8724429/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com