gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 01:57:56 25 4
gpt4 key购买 nike

我被这个问题困扰了:

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

        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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com