I am making a program that draws a circle on a JFrame. I want to start the program with the circle in the center of the screen so that even if the size of the JFrame window is changed, it is still centered. How would I do it? I have tried different things but haven't found anything that works yet. The code is down below:
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class ImageFrame extends JFrame {
private static final long serialVersionUID = 1L;
int width = 40;
int height = 40;
int x = 160;
int y = 70;
JPanel panel = new JPanel() {
private static final long serialVersionUID = 1L;
public void paintComponent(Graphics g) {
super.paintComponents(g);
g.drawOval(x, y, width, height);
}
};
public ImageFrame() {
add(panel);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(400, 300);
setLocationRelativeTo(null);
setVisible(true);
}
}
This is a simple math problem. Divide the difference of the container width and the circle width by 2 to locate the x co-ordinate for drawOval. Do the same for the height for the y co-ordinate.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With