我正在尝试编写一个程序,如果右键单击该形状,可以删除该形状。我的方法是包括一种方法,该方法可以找到形状的最小和最大X和Y坐标,如果单击的X和Y坐标在这些坐标之间,则在鼠标单击时将其删除。现在,我的代码只是删除形状数组列表中产生的最后一个形状。
public class RemoveCircle extends JPanel
{
private JFrame framey;
private JPanel panels1;
Circle c1 = new Circle(100,100);
private int x, y;
MouseClicks ms1;
ArrayList<Circle> circles = new ArrayList<Circle>();
private int clickcount;
public RemoveCircle()
{
framey = new JFrame("RemoveCircle");
framey.setSize(900,900);
ms1 = new MouseClicks();
//circles.add(new Circle(x,y));//This may be the original circle being added
this.setBackground(Color.BLACK);
this.setPreferredSize(new Dimension(900,900));
framey.add(this);
framey.pack();
framey.setVisible(true);
this.addMouseListener(ms1);
}
public class Circle
{
int x, y;
Color c1;
int minsx, maxsx, minsy, maxsy;
public Circle(int x, int y)
{
this.x = x; this.y = y;
c1 = getRandoColor();
}
public void draw(Graphics g)
{
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(c1);
g2d.fillOval(x,y,50,50);
}
Random numGenerator = new Random();
private Color getRandoColor()
{
return new Color(numGenerator.nextInt(255), numGenerator.nextInt(255), numGenerator.nextInt(255));
}
public int getMinY(int y)
{minsy = y - 25; return minsy; }
public int getMaxY(int y)
{maxsy = y + 25; return maxsy; }
public int getMinX(int x)
{minsx = x - 25; return minsx; }
public int getMaxX(int x)
{maxsx = x + 25; return maxsx; }
}
@Override
protected void paintComponent(Graphics g)
{
//if (clickcount < 10)
{
super.paintComponent(g);
for (Circle cr : circles)
cr.draw(g);
}
}
public class MouseClicks implements MouseListener
{
int b, y, x ;
int circlecount;
public void mouseClicked(MouseEvent m)
{
int x = m.getX(), y = m.getY(); b = m.getButton();
this.x = x;
this.y = y;
if (b == 1 && circlecount < 10) //Left Click
{
circles.add(new Circle(x-25, y-25)); //x-40 and y - 75
RemoveCircle.this.repaint();
circlecount++;
}
if (b == 3) //Left Click
{ for (Circle c : circles)
{
if ((x >= c.getMinX(x) && x <= c.getMaxX(x)) && (y >= c.getMinY(y) && y <= c.getMaxY(y)))
{
circles.remove(c);
RemoveCircle.this.repaint();
circlecount--;
}
}
}
}
public void mouseExited(MouseEvent m) {}
public void mousePressed(MouseEvent m) {}
public void mouseEntered(MouseEvent m) {}
public void mouseReleased(MouseEvent m) {}
}
}
答案 0 :(得分:1)
更简单的方法是利用Shape
界面。形状可以是圆形或矩形等。然后,您可以使用Shape.contains(...)
方法确定鼠标单击是否在形状的边界内。
因此,您无需创建Circle
类,而是创建具有两个属性的ShapeInfo
类:
您将此对象存储在ArrayList
中,现在绘制逻辑变为:
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
for (ShapeInfo info : shapes)
{
g2d.setColor( info.getColor() );
g2d.draw( info.getShape() );
}
然后,MouseListner中的代码将遍历相同的ArrayList,并在每个contains(...)
上调用Shape
方法。找到匹配项后,将其从ArrayList中删除。
您可以将Ellipse2D.Double类用于圆形。请查看Custom Painting Approaches中的DrawOnComponent
示例,以了解使用此基本方法绘制矩形的示例。