I am trying to Center an oval drawn with JFrame
& Color
but I don't know how I would do this.
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. If I add a parameter to the Method, JFrame it doesn't work.
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.
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);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.