![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 import javax.swing.*; 2 import java.awt.*; 3 import java.awt.event.*; 4 import java.util.ArrayList; 5 6 public class Test_16_23 extends JFrame{ 7 private ArrayList xArray = new ArrayList(); 8 private ArrayList yArray = new ArrayList(); 9 10 private int xPoint,yPoint; 11 private int radius = 5; 12 private boolean draw = false; 13 14 public Test_16_23(){ 15 add(new JP()); 16 } 17 18 public static void main(String[] args) { 19 JFrame frame = new Test_16_23(); 20 frame.setTitle("Test_16_23"); 21 frame.setSize(300, 300); 22 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 23 frame.setLocationRelativeTo(null); 24 frame.setVisible(true); 25 } 26 27 class JP extends JPanel{ 28 private int x1,y1,x2,y2; 29 30 public JP(){ 31 addMouseListener(new MouseAdapter(){ 32 public void mouseClicked(MouseEvent e){ 33 xPoint = e.getX(); 34 yPoint = e.getY(); 35 draw = true; 36 xArray.add(xPoint); 37 yArray.add(yPoint); 38 39 repaint(); 40 } 41 }); 42 } 43 44 protected void paintComponent(Graphics g){ 45 super.paintComponent(g); 46 47 for(int i = 0; i < xArray.size(); i++){ 48 if(draw) 49 //画空心圈 50 g.drawOval((Integer.parseInt(xArray.get(i).toString()))-radius,(Integer.parseInt(yArray.get(i).toString()))-radius, 2*radius, 2*radius); 51 } 52 //如果点超过2个,再填充 53 if(xArray.size() > 1) 54 { 55 findTheNearest(); 56 g.fillOval((Integer.parseInt(xArray.get(x1).toString()))-radius,(Integer.parseInt(yArray.get(y1).toString()))-radius, 2*radius, 2*radius); 57 g.fillOval((Integer.parseInt(xArray.get(x2).toString()))-radius,(Integer.parseInt(yArray.get(y2).toString()))-radius, 2*radius, 2*radius); 58 } 59 60 } 61 62 public void findTheNearest(){ 63 //第一对点赋值 64 x1 = y1 = 0; 65 x2 = y2 = 1; 66 double Value = 0; 67 double minValue = theDistance(Integer.parseInt(xArray.get(0).toString()),Integer.parseInt(yArray.get(0).toString()), 68 Integer.parseInt(xArray.get(1).toString()),Integer.parseInt(yArray.get(1).toString())); 69 //利用两层循环达到遍历所有点间距的目的 70 for(int i = 0; i < xArray.size(); i++){ 71 for(int j = i + 1; j < xArray.size(); j++){ 72 Value = theDistance(Integer.parseInt(xArray.get(i).toString()),Integer.parseInt(yArray.get(i).toString()),Integer.parseInt(xArray.get(j).toString()), 73 Integer.parseInt(yArray.get(j).toString())); 74 if(Value < minValue) 75 { 76 minValue = Value; 77 x1 = y1 = i; 78 x2 = y2 = j; 79 } 80 } 81 } 82 } 83 84 public double theDistance(int x1, int y1, int x2, int y2){ 85 return Math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2)); 86 } 87 } 88 }
效果图: