几何:最接近的一对

时间:2014-01-22 19:37:31

标签: java arraylist mouseevent points closest

本周我在java的作业上有些困惑。问题听起来像这样: “编写一个允许用户点击面板动态创建点的程序。最初,面板为空。当面板有两个或多个点时,突出显示最近的点对。每当创建一个新点时,一对新的点突出显示最近点的位置。使用小圆圈显示点并使用实心圆圈突出显示点。(提示:将点存储在ArrayList中)“

在我的代码下我试图制作CircleMouse类的ArrayList,但我不知道这是否是“正确”的方法呢?另外,当它们在ArrayList中时,如何在面板中显示圆圈?

import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.util.ArrayList;

import javax.swing.*;

class ClosestPairOfPoints extends JFrame {

  /** FRIE VARIABLER **/
  int x, y;

  /*** ARRAYLIST MED ALLE SIRKLENE ***/
  public ArrayList<CircleMouse> arrCircle = new ArrayList <CircleMouse>();

  public ClosestPairOfPoints() {
    /*** PANEL FOR Å HOLDE PÅ SIRKLENE ***/
    JPanel circlePanel = new JPanel();
    circlePanel.setSize(500, 400);
    circlePanel.setLocation(0, 0);
    circlePanel.setBackground(Color.PINK);

    /*** HENTER CIRCLEMOUSE KLASSEN INN ***/
    CircleMouse circleMouse = new CircleMouse();
    circlePanel.addMouseListener(circleMouse);
    circlePanel.addMouseMotionListener(circleMouse);

    /*** LEGGER PANELET INN I FRAMEN ***/
    add(circlePanel);

}

/*** CIRCLEMOTION KLASSEN ***/
class CircleMouse extends JPanel implements MouseListener, MouseMotionListener {

    public void paintComponent (Graphics g) {
        super.paintComponent(g);
        g.setColor(Color.BLUE);
        g.drawOval(x, y, 15, 15);
    }

    @Override
    public void mouseDragged(MouseEvent e) {
        // TODO Auto-generated method stub

    }

    @Override
    public void mouseMoved(MouseEvent e) {
        // TODO Auto-generated method stub

    }

    @Override
    public void mouseClicked(MouseEvent e) {
        x = e.getX();
        y = e.getY();
        repaint();


    }

    @Override
    public void mouseEntered(MouseEvent e) {
        // TODO Auto-generated method stub

    }

    @Override
    public void mouseExited(MouseEvent e) {
        // TODO Auto-generated method stub

    }

    @Override
    public void mousePressed(MouseEvent e) {
        // TODO Auto-generated method stub

    }

    @Override
    public void mouseReleased(MouseEvent e) {
        // TODO Auto-generated method stub

    }

}

public static void main(String[] args) {
    ClosestPairOfPoints frame = new ClosestPairOfPoints();
    frame.setTitle("Øving 1 - Oppgave 1: Closest Pair Of Points");
    frame.setLocationRelativeTo(null);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(500, 400);
    frame.setVisible(true);
}

}

1 个答案:

答案 0 :(得分:0)

  

我试图制作CircleMouse类的ArrayList

听起来不太对劲。您应该ArrayList Point。每次调用mouseClicked时,都应该将Point添加到MouseEvent,然后添加paintComponent方法,您应该遍历此列表并绘制“点”

例如......