如何在绘图面板上选择形状?
我正在创建一个程序,可以在画布上绘制不同的形状。我想添加一个按钮,单击该按钮后,我可以选择一个形状,然后将其拖动/翻译到画布上的不同位置。实现这一点背后的基本理念是什么?当我单击形状以选择它时,我想以某种方式在其周围添加边框以表明它已被选中。
好的,我尝试过这个,它确实有效。除此之外,我可以选择多个形状,并且显示其所选形状的边框不会出现在形状周围,直到我更改单选按钮以执行其他操作之后。然后出现选择。我不知道如何解决这个问题?我尝试添加一个布尔值来修复能够选择多个形状的问题,但它不起作用。 boolean isSelected 最初设置为 false。我不明白为什么单击鼠标时不会自动显示边框颜色/宽度。
public void mousePressed(MouseEvent e) {
if ((_buttonNumber == 0) || (isSelected)) {
for(int i=0; i<_storedShapes.size(); i++) {
_storedShapes.elementAt(i).contains(e.getPoint());
_storedShapes.elementAt(i).setBorderWidth(10);
_storedShapes.elementAt(i).setBorderColor(Color.BLACK);
isSelected = true;
}
}
else {
isSelected = false;
}
I am creating a program where I can draw different shapes onto a drawing canvas. I want to add a button that, after clicked, allows me to select a shape and then drag/translate it to a different spot on the canvas. What is the basic concept behind implementing this? When I click on the shape to select it, I want to somehow add a border around it to show that it is selected.
Okay, I tried this and it kind of works. Except, I am able to select multiple shapes and the border that shows its selected does not appear around the shape until after I change radio buttons to do something else. Then the selection appears. I am not sure how to fix this? I tried adding a boolean to fix being able to select multiple shapes, but it isn't working. boolean isSelected is originally set to false. I don't understand why the border color/width doesn't appear automatically on the mouse click.
public void mousePressed(MouseEvent e) {
if ((_buttonNumber == 0) || (isSelected)) {
for(int i=0; i<_storedShapes.size(); i++) {
_storedShapes.elementAt(i).contains(e.getPoint());
_storedShapes.elementAt(i).setBorderWidth(10);
_storedShapes.elementAt(i).setBorderColor(Color.BLACK);
isSelected = true;
}
}
else {
isSelected = false;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将整个项目分解为小步骤,并单独单独解决每个步骤。首先弄清楚如何从多个Shape中选择一个Shape。我通常通过将形状保存在 ArrayList 中,然后在 MouseListener 的 mousePressed 方法中迭代列表并检查是否有任何形状包含(...)来完成此操作。代码> 鼠标的点。
对于拖动,您将使用 MouseMotionListener(这两个侦听器可以合并在一个扩展 MouseAdapter 的类中),然后在
mouseDragged
方法中移动选定的形状。Break down this overall project into small steps and solve each one individually and in isolation. First figure out how to select a Shape among several Shapes. I've usually done this by holding my Shapes in an ArrayList, then in a MouseListener's
mousePressed
method, iterating through the list and checking to see if any Shapecontains(...)
the mouse's Point.For Dragging, you'll use a MouseMotionListener (the two listener's can be combined in one class that extends MouseAdapter) and then move the selected shape in the
mouseDragged
method.