[英]How do I center drawn things in JFrame?
I am trying to Center an oval drawn with JFrame
& Color
but I don't know how I would do this. 我试图将用JFrame
和Color
绘制的椭圆中心,但我不知道如何做到这一点。
I know that I can get get the width by using Jframe#width()
but I don't know how to do this in the method paintComponent
, where I draw my circle. 我知道我可以通过使用Jframe#width()
获得宽度,但我不知道如何在paintComponent
方法中执行此操作,我绘制圆圈。 If I add a parameter to the Method, JFrame it doesn't work. 如果我向Method添加一个参数,JFrame它不起作用。
import javax.swing.*;
import java.awt.Graphics;
import java.awt.Color;
public class AU19b extends JPanel{
protected void paintComponent(Graphics g){
g.setColor(Color.RED);
g.drawOval(10,10, 50, 50);
}
public static void main(String[] args){
JFrame f = new JFrame("Sebastians GUI");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(400, 250);
f.add(new AU19b());
f.setVisible(true);
}
}
use this to draw a circle with radius 50. 用它来画一个半径为50的圆。
import javax.swing.*;
import java.awt.Graphics;
import java.awt.Color;
public class AU19b extends JPanel{
@Override
public void paintComponent(Graphics g){
g.setColor(Color.RED);
int radius = 50;
g.drawOval(getWidth()/2 - radius,getHeight()/2 - radius, 2*radius, 2*radius);
}
public static void main(String[] args){
JFrame f = new JFrame("Sebastians GUI");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(400, 250);
f.add(new AU19b());
f.setVisible(true);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.