I need to draw a simple circle by using mouse clicks First click will be the center Second will be the radius and the circle would be draw by the 2.
Thanks in advance
I need to draw a simple circle by using mouse clicks First click will be the center Second will be the radius and the circle would be draw by the 2.
Thanks in advance
Good question! The code below is a self contained example (I'm using dragging to define the radius):
public static void main(String[] args) throws IOException {
JFrame frame = new JFrame("Test");
frame.add(new JComponent() {
Point p; int r;
{
addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
p = e.getPoint(); r = 0; repaint();
}
public void mouseReleased(MouseEvent e) {
r = (int) Math.round(e.getPoint().distance(p));
repaint();
}
});
addMouseMotionListener(new MouseMotionAdapter() {
public void mouseDragged(MouseEvent e) {
r = (int) Math.round(e.getPoint().distance(p));
repaint();
}
});
setPreferredSize(new Dimension(400, 300));
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if(p != null) g.drawOval(p.x - r, p.y - r, 2 * r, 2 * r);
}
});
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) throws IOException {
JFrame frame = new JFrame("Test");
frame.add(new JComponent() {
Point p1, p2;
{
addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (p1 == null || p2 != null) {
p1 = e.getPoint();
p2 = null;
} else {
p2 = e.getPoint();
}
repaint();
}
});
setPreferredSize(new Dimension(400, 300));
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if(p1 != null && p2 != null) {
int r = (int) Math.round(p1.distance(p2));
g.drawOval(p1.x - r, p1.y - r, 2 * r, 2 * r);
}
}
});
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}