为了家庭作业,我想在屏幕周围随机画圈。如果任何圆圈重叠,那么我想填充这些圆圈。我从一些代码开始,这些代码在单击鼠标指针的任何地方在屏幕上绘制圆圈。我真的很困惑如何使用随机值来确定圆圈以及如何将这些值存储在数组或数组列表中。我认为为了填充圆圈,我将只使用一个 for 语句来比较圆心之间的距离。非常感谢您的任何建议。这是我试图弄清楚如何修改的起点:
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) {}
}
}
最佳答案
你想用
Math.random()
or the Random class
As this it homework, I don't want to give you the full solution. But..
Here is a hint.
Replace the addMouseListener with a loop, to draw the number of circles on the screen.
Inside the loop, is one of the random methods to get 2 value for X and Y to create your Point object, and add it to the array.
To use the Random object, your code will look like this
Random random = new Random();
int x = random.nextInt(200);
200 是最大数字,这就是您的屏幕尺寸。
关于java - 绘制随机圆圈,将它们的坐标存储在数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4197027/