我在使用将元素(绘制的矩形和椭圆)存储在 ArrayList 中的图形绘制程序时遇到问题。我想从列表中删除特定的矩形和椭圆形,方法是首先用鼠标左键选择元素,然后使用鼠标右键将其删除。但是,问题是我的程序将删除未先通过鼠标左键选择的矩形或椭圆形(即,我可以右键单击任何节点,它将在选择之前将其删除)。
我已将 GraphElements 的 ArrayList 声明为
ArrayList <GraphElement> element = new ArrayList<GraphElement>();
在 MousePressListener 内部,我遇到困难的部分是(代码的 setLabel 部分与我的下一个问题相关):
for (int i = 0; i < element.size(); i++)
{
GraphElement el = (GraphElement)element.get(i);
el.isSelected(x, y); // isSelected method (functioning correctly) to check whether the coordinates are inside the bounds of the rectangle or ellipse
if (el.isSelected(x,y))
{
if (event.getButton() == MouseEvent.BUTTON3) // delete a node
element.remove(i).isSelected(x, y);
if (setLabel)
{
el.setLabel(label);
setLabel = false;
repaint();
}
}
}
其次,我想向选定的矩形或椭圆添加标签。在我的程序中,这是通过选择矩形或椭圆形来添加文本、在 JTextField 中输入文本,然后选择 JButton 以应用更改来完成的。但是,我的问题是,按下 JButton 后,标签没有绘制在组件上。我必须再次按下鼠标按钮才能显示文本。我想这是因为我的 MousePressListener 中有 setLabel 。但我需要在添加文本之前选择元素,所以我不知道如何处理。
这是标签的 ActionListener:
class addLabel implements ActionListener {
public void actionPerformed(ActionEvent e)
{
component.setLabel(labelField.getText());
}
}
addLabel label = new addLabel();
labelButton.addActionListener(label);
我很感激任何帮助。谢谢。
最佳答案
这个说法看起来非常可疑:
element.remove(i).isSelected(x, y);
好像是这样的
"remove the ith element from the list, AND THEN test to see if
x, y
is within it"
您想要在删除第 i 个元素之前测试它是否已被选中。
关于Java:从 ArrayList 中删除元素并添加文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9459920/