对于作业,我想在屏幕上随机画圆圈。如果任何圆圈重叠,那么我想填写这些圆圈。我开始使用一些代码,无论单击鼠标指针,都会在屏幕上绘制圆圈。我真的很困惑如何使用随机值来确定圆圈以及如何将这些值存储在数组或arraylist中。我认为,为了填写圆圈,我将使用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) {}
}
}
答案 0 :(得分:1)
您想要使用
Math.random()
或Random类
由于这是家庭作业,我不想给你完整的解决方案。但..
这是一个提示。
用循环替换addMouseListener,以在屏幕上绘制圆圈数。
在循环内部,是获取X和Y的2值以创建Point对象的随机方法之一,并将其添加到数组中。
要使用Random对象,您的代码将如下所示
Random random = new Random();
int x = random.nextInt(200);
如果200是最大数字,这将是您屏幕的大小。