我需要使用鼠标单击绘制一个简单的圆第一次单击将是中心第二次将是半径,圆将由 2 绘制。
提前致谢
好问题!下面的代码是一个自包含的示例(我使用拖动来定义半径):
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);
}