I have developed a telecommunication application for locating signal strengths from the towers. I have used java swing and I'm having a problem when drawing the circle around the given point of the mobile signal transmitter tower location. I have already calculated the X, Y coordinates and also the radius value.
Please find the below code which I've used to draw the circle and it is having issues.
JPanel panelBgImg = new JPanel() {
public void paintComponent(Graphics g) {
g.drawOval(X, Y, r, r);
}
}
The issue is, it creates the circle but it didn't take the X and Y coordinates as the center point. It took the X and Y coordinates as the top left point of the circle.
Could anyone please help me to draw the circle by having the given X and Y coordinates as the center point of the circle.
This question is related to
java
swing
jpanel
java-2d
paintcomponent
Replace your draw line with
g.drawOval(X - r, Y - r, r, r)
This should make the top-left of your circle the right place to make the center be (X,Y)
,
at least as long as the point (X - r,Y - r)
has both components in range.
This draws an arc with the center in the specified rectangle. You can draw, half-circles, quarter-circles, etc.
g.drawArc(x - r, y - r, r * 2, r * 2, 0, 360)
JPanel pnlCircle = new JPanel() {
public void paintComponent(Graphics g) {
int X=100;
int Y=100;
int d=200;
g.drawOval(X, Y, d, d);
}
};
you can change X,Y coordinates and radius what you want.
both answers are is incorrect. it should read:
x-=r;
y-=r;
drawOval(x,y,r*2,r*2);
drawCircle(int X, int Y, int Radius, ColorFill, Graphics gObj)
So we are all doing the same home work?
Strange how the most up-voted answer is wrong. Remember, draw/fillOval take height and width as parameters, not the radius. So to correctly draw and center a circle with user-provided x, y, and radius values you would do something like this:
public static void drawCircle(Graphics g, int x, int y, int radius) {
int diameter = radius * 2;
//shift x and y by the radius of the circle in order to correctly center it
g.fillOval(x - radius, y - radius, diameter, diameter);
}
The only thing that worked for me:
g.drawOval((getWidth()-200)/2,(getHeight()-200)/2, 200, 200);
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Graphics;
import javax.swing.JFrame;
public class Graphiic
{
public Graphics GClass;
public Graphics2D G2D;
public void Draw_Circle(JFrame jf,int radius , int xLocation, int yLocation)
{
GClass = jf.getGraphics();
GClass.setPaintMode();
GClass.setColor(Color.MAGENTA);
GClass.fillArc(xLocation, yLocation, radius, radius, 0, 360);
GClass.drawLine(100, 100, 200, 200);
}
}
Source: Stackoverflow.com