1

我正在编写一个摆动的应用程序,并且我有一个绘制正在拖动的对象的组件。这是代码的一小部分:

public class DragPanel extends JComponent{

    private final int CARD_STACK_SPACING;
    private int x, y;
    private List<Card> cards;

    public DragPanel(int cardStackSpacing) {
        x = -1;
        y = -1;
        cards = null;
        CARD_STACK_SPACING = cardStackSpacing;
    }

    public void drag(int x, int y, Card card) {
        this.x = x;
        this.y = y;
        cards = new ArrayList<Card>();
        cards.add(card);
        repaint();
    }
    public void dragCards(int x, int y, List<Card> cards) {
        this.x = x;
        this.y = y;
        this.cards = cards;
        repaint();
    }
    public void stopDragging() {
        x = -1;
        y = -1;
        cards = null;
        repaint();
    }

    @Override
    public void paintComponent(Graphics g) {
        if (x > 0 && y > 0) {
            Graphics2D g2d = (Graphics2D) g;
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            int adjustedY = y;
            for (int i = 0; i < cards.size(); ++i) {
                CardImager.drawCard(cards.get(i), g2d, x, adjustedY);
                adjustedY += CARD_STACK_SPACING;
            }
        }
    }
}

现在,当我运行这段代码时,我得到一个ConcurrentModificationException,我认为这是因为我有一个 for 循环,paintComponent它遍历卡片列表,并且我还有将卡片列表设置为不同内容的方法。

我的问题是,我能做些什么来确保不会发生这种情况?

编辑:这里有一些更多的信息,当鼠标被拖动时,这个方法被调用,它从上面的dragPanel调用dragCards方法。

@Override
public void mouseDragged(MouseEvent e) {
    firstClick = 0;
    if (!isDragging &&
            !isDraggingStack &&
            e.getSource() instanceof ResultDisplay && 
            searchPanel.getCard(e.getX(), e.getY()) != null) {

        isDragging = true;
        draggingCard = searchPanel.getCard(e.getX(), e.getY());
        offsets = searchPanel.getOffsets(e.getX(), e.getY());
        dragPanel.drag(e.getX() + offsets[0], e.getY() + offsets[1], draggingCard);

    } else if (!isDragging &&
            !isDraggingStack &&
            e.getSource() instanceof DeckBuilderPanel &&
            deckBuilderPanel.getCard(e.getX(), e.getY()) != null) {

        isDraggingStack = true;
        offsets = deckBuilderPanel.getOffsets(e.getX(), e.getY());
        draggingCardStack = deckBuilderPanel.removeCardStack(e.getX(), e.getY());
        dragPanel.dragCards(e.getX() + offsets[0], e.getY() + offsets[1] + searchPanel.getHeight(), draggingCardStack);
        System.out.println(offsets[0] + " " + offsets[1]);
    }
    if (isDragging && !isDraggingStack) {
        dragPanel.drag(e.getX() + offsets[0], e.getY() + offsets[1], draggingCard);
    } else if (!isDragging && isDraggingStack) {
        dragPanel.dragCards(e.getX() + offsets[0], e.getY() + offsets[1] + searchPanel.getHeight(), draggingCardStack);
    }
}
4

0 回答 0