2
爲了做作業,我想隨機在屏幕上繪製圓圈。如果任何一個圓圈重疊,那麼我想填寫這些圓圈。我開始使用一些代碼,在點擊鼠標指針的任何地方在屏幕上繪製圓圈。我對如何使用隨機值來確定圓以及如何將這些值存儲在數組或數組列表中感到困惑。我認爲要填充圓圈,我只會使用for語句來比較圓圈中心點之間的距離。非常感謝您的任何建議。這裏是我試圖找出如何修改我的出發點:繪製隨機圓圈,將它們的coorindates存儲在數組中
import java.util.ArrayList;
import javax.swing.JPanel;
import java.awt.*;
import java.awt.event.*;
public class DotsPanel extends JPanel
{
private final int SIZE = 6; // radius of each dot
private ArrayList<Point> pointList;
//-----------------------------------------------------------------
// Constructor: Sets up this panel to listen for mouse events.
//-----------------------------------------------------------------
public DotsPanel()
{
pointList = new ArrayList<Point>();
addMouseListener (new DotsListener());
setBackground (Color.black);
setPreferredSize (new Dimension(300, 200));
}
//-----------------------------------------------------------------
// Draws all of the dots stored in the list.
//-----------------------------------------------------------------
public void paintComponent (Graphics page)
{
super.paintComponent(page);
page.setColor (Color.green);
for (Point spot : pointList)
page.fillOval (spot.x-SIZE, spot.y-SIZE, SIZE*2, SIZE*2);
page.drawString ("Count: " + pointList.size(), 5, 15);
}
//*****************************************************************
// Represents the listener for mouse events.
//*****************************************************************
private class DotsListener implements MouseListener
{
//--------------------------------------------------------------
// Adds the current point to the list of points and redraws
// the panel whenever the mouse button is pressed.
//--------------------------------------------------------------
public void mousePressed (MouseEvent event)
{
pointList.add(event.getPoint());
repaint();
}
//--------------------------------------------------------------
// Provide empty definitions for unused event methods.
//--------------------------------------------------------------
public void mouseClicked (MouseEvent event) {}
public void mouseReleased (MouseEvent event) {}
public void mouseEntered (MouseEvent event) {}
public void mouseExited (MouseEvent event) {}
}
}