java - 同时选择两个或多个形状

标签 java 2d drawing draw shapes

我被这个问题困扰了:

当我单击形状内部(有一个矩形和圆形的数组列表)时,我选择它(仅用于调试,将其颜色更改为蓝色)。因此,如果我在外部空白处单击,我会取消选择它(仅用于调试,将其颜色更改为之前的颜色)。

        for(int i=0; i<images.size(); i++){
        //checking if the click is inside a shape
            if((images.get(i).getLocation().getX() < e.getX() && images.get(i).getLocation().getY() < e.getY() && images.get(i).getX() + images.get(i).getWidth() > e.getX() && images.get(i).getLocation().getY() + images.get(i).getHeight() > e.getY())){ 
                images.get(i).setColor(Color.BLUE);
                images.get(i).setIsSelected(true);
        //debugging
                JOptionPane.showMessageDialog(null, images.get(i).getIsSelected());
                repaint();
                //JOptionPane.showMessageDialog(null, colors.get(i));
            }
            else{
                images.get(i).setColor(colors.get(i));
        //debugging
                JOptionPane.showMessageDialog(null, images.get(i).getIsSelected());
                images.get(i).setIsSelected(false);
                repaint();
                }

For example, imagine 2 circles and 1 rectangle, all in black. My code has the following workflow:

  • Click inside the Rectangle
  • Change its color to BLUE
  • Just for debugging, it prints "selected == true" (for the rectangle), "selected = false" (for the 1st circle), "selected = false", (for the 2nd circle)
  • Click in a blank space
  • Change the rectangle's color to the previous color (black)
  • Just for debugging, it prints "selected == false" (for the rectangle), "selected = false" (for the 1st circle), "selected = false", (for the 2nd circle)
  • Click inside the Rectangle again
  • Change its color to BLUE
  • Just for debugging, it prints "selected == true" (for the rectangle), "selected = false" (for the 1st circle), "selected = false", (for the 2nd circle)
  • Click inside a Circle
  • Change its color to BLUE
  • Just for debugging, it prints "selected == true" (for the rectangle), "selected = true" (for the 1st circle), "selected = false", (for the 2nd circle)
  • The problem is: the rectangle's color turns back to BLACK. It should be still BLUE.

如何同时选择 2 个或更多形状?

最佳答案

您的“if”子句设置最近选择的项目的颜色并将其设置为已选择; “else”子句将所有其他项目重置为未选择状态并重置颜色。

这不是正确的方法。

您应该有一个 Shape 类来保存图像及其所有属性。这些属性之一是当前是否选择该形状。然后,当您重新绘制时,将 Graphics 传递给 Shape 类中的一个方法,该方法将图像重新绘制为选定或未选定。

您应该在单独的循环中将所有项目设置为未选择,并且仅当第一个循环未确定单击位于对象中时才会进入该循环。

boolean found = false;
for ( Shape s : images ) {
  if ( click is in s ) {
     s.setSelected(true);
     found = true;
     break;
   }
} 
if ( !found ) {
   // set all images to unselected here
}
repaint();

关于java - 同时选择两个或多个形状,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52065316/

相关文章:

graphics - 如何测试线段是否与二维轴对齐矩形相交?

java - 使用数组存储纳税人信息

java - 如何在 Jersy 响应中设置缓存控制 header

java - iPhone 形状库

c# - 将箭头形状连接到字符串

Java:循环增量不从 0 开始

ios - drawRect - 绘制星形

java - 读取文本文件中指定数量的字符

java - LibGDX XLib 扩展 : "GLX" Error

java - Java 中简单 2D 动画的框架/库?