我正在尝试编写一个程序,如果鼠标右键单击在形状内部,则该程序将允许我删除该形状。我的方法是包含一种方法来查找形状的最小和最大 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) {}
}
}
最佳答案
更简单的方法是利用 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,并在每个 Shape
上调用 contains(...)
方法。当您找到匹配项时,您可以从 ArrayList 中删除该条目。
您可以使用 Ellipse2D.Double 类来表示圆形。查看 Custom Painting Approaches 中的 DrawOnComponent
示例例如使用这种基本方法绘制矩形。
关于java - 单击内部区域后删除形状,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53141693/