用java随机画出两个圆,判断它们是否相交


import java.awt.*;
import java.util.Random;
import javax.swing.*;
import javax.swing.border.TitledBorder;

/***
7. * 随机画出两个圆,判断它们是否相交
8. * @author Firklaag
9. * @ver 0.01
10. * 编写代码实现同一平面内两圆是否碰撞,其中:第一个圆圆心坐标为(x1,y1),
半径是r1,第二个圆圆心坐标为(x2,y2),
半径是r2,数据结构自定义。
11. */
public class CheckCircul extends JFrame {
//定义画布
private MyPanel myPanel = new MyPanel();

public CheckCircul() {
add(myPanel);
}

public static void main(String[] args) {
CheckCircul demo = new CheckCircul();
run(demo, 800, 700);
}
/*
* 运行辅助方法
*/
public static void run(final JFrame f, final int width, final int height) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
f.setTitle(f.getClass().getSimpleName());
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(width, height);
f.setVisible(true);
}
});
}

}
/*
40. * 画布类
41. */
class MyPanel extends JPanel {
//定义标签
private JLabel label = new JLabel();
//定义随机数
private Random ran = new Random();
//定义两个圆
private Circul tom;
private Circul jerry;

/**
52. * 生成两个圆并增加标签到画布
53. */
public MyPanel() {
tom = new Circul(ran.nextInt(300), ran.nextInt(300), ran.nextInt(400));
jerry = new Circul(ran.nextInt(300), ran.nextInt(300), ran.nextInt(400));
this.setBorder(new TitledBorder("CheckCircul"));
add(label);
}

@Override
protected void paintComponent(Graphics g) {
//画出两个圆
Rectangle rec1 = tom.draw(g);
Rectangle rec2 = jerry.draw(g);
//判断其是否相交
if (rec1.intersects(rec2)) {
label.setText("相交");
} else {
label.setText("不相交");
}
}

}
/**
76. * 定义圆形类,类中不仅有圆的属性,还有画圆的方法
77. */
class Circul {
private int x;
private int y;
private int r;

public Circul(int x, int y, int r) {
this.x = x;
this.y = y;
this.r = r;
}

public Rectangle draw(Graphics g) {
Graphics2D g2d = (Graphics2D) g.create();
//调用抗锯齿API
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2d.drawOval(x, y, r, r);
return new Rectangle(x, y, r, r);

}
public int getX() {
return x;
}

public void setX(int x) {
this.x = x;
}

public int getY() {
return y;
}

public void setY(int y) {
this.y = y;
}
public int getR() {
return r;
}

public void setR(int r) {
this.r = r;
}
}

你可能感兴趣的:(Java)