Java游戏 - 混合使用MousePressed和MouseClicked

时间:2017-02-24 23:47:36

标签: java swing user-interface mouselistener inventory

我目前正试图设置我自己的java游戏,而不使用任何额外的库来挑战自己。现在我正在为我的RPG编制库存系统。

我的目标是能够点击清单中的项目并单击目标点(2x MouseClicked),并将项目从一个库存槽拖到另一个(1x MousePressed,1x MouseReleased)。事件由JFrame上的MouseListener接口实现的方法调用。

如果我实现一个没有另一个,它工作正常,但如果我使用两个代码片段,MousePressed函数似乎干扰我想要使用MouseClicked删除项目。

继承我的代码:

@Override
public void mouseClicked(MouseEvent me) {
    // TODO Auto-generated method stub

        if(bag.isItemGrabbed())
        {
            bag.deployItem();
        }

        else if(!(bag.isItemGrabbed()))
        {
            bag.grabItem();
        }
    }

@Override
public void mousePressed(MouseEvent arg0) {
    // TODO Auto-generated method stub

    if(!(bag.isItemGrabbed()))
    {
        bag.grabItem();
    }
}

@Override
public void mouseReleased(MouseEvent arg0) {
    // TODO Auto-generated method stub

    if(bag.isItemGrabbed())
    {
        bag.deployItem();
    }
}

grabItem方法:

public void grabItem()
{
    if(inventoryHover>=0)
    {
        grabbedItem = inventorySlots[inventoryHover];
        grabbedItemQuantity = inventorySlotQuantities[inventoryHover];
        grabbedItemPreviousSlot = inventoryHover;
        inventorySlots[inventoryHover] = null;
        inventorySlotQuantities[inventoryHover] = 0;
    }
}

itemDeploy方法:

public void deployItem()
{
    if(isItemGrabbed()&&inventoryHover>=0)
    {
        if(inventorySlots[inventoryHover]!=null)
        {
                inventorySlots[grabbedItemPreviousSlot]=inventorySlots[inventoryHover];
                inventorySlotQuantities[grabbedItemPreviousSlot]=inventorySlotQuantities[inventoryHover];
                inventorySlots[inventoryHover]=grabbedItem;
                inventorySlotQuantities[inventoryHover]=inventorySlotQuantities[grabbedItemQuantity];
                grabbedItem=null;
                grabbedItemQuantity = 0;
                grabbedItemPreviousSlot = -1;
        }
        else
        {
                inventorySlots[inventoryHover]=grabbedItem;
                inventorySlotQuantities[inventoryHover]=inventorySlotQuantities[grabbedItemQuantity];
                grabbedItem=null;
                grabbedItemQuantity = 0;
                grabbedItemPreviousSlot = -1;
        }
    }
    else if(isItemGrabbed()&&inventoryHover==-1)
    {
            grabbedItem=null;
            grabbedItemQuantity = 0;
            grabbedItemPreviousSlot = -1;
    }
}

正如我所说:如果同时使用Pressed和Clicked我可以使用拖放功能,但是如果我想要两次单击,则该项目不会被删除。

提前致谢!

0 个答案:

没有答案