Jump to content

[1.14.4] get item out slot of lazyoptional<IItemHandler>?


Kenneth201998

Recommended Posts

I have this line of code in my block's tile entity:

private LazyOptional<IItemHandler> handler = LazyOptional.of(this::createHandler);

And this code in my block's container:

this.tile_entity.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY).ifPresent(h -> {
	this.addSlot(new SlotItemHandler(h, 0, 26, 21));
	this.addSlot(new SlotItemHandler(h, 1, 26, 48));
	this.addSlot(new SlotItemHandler(h, 2, 80, 35));
});

And this code also in my block's tile entity:

private IItemHandler createHandler() {
		return new ItemStackHandler(3) {
			@Override
			protected void onContentsChanged(int slot) {
				markDirty();
			}
			@Override
            public boolean isItemValid(int slot, @Nonnull ItemStack stack) {
				if(slot != 2) {
                	return true;
                } else {
                	return false;
                }
            }
            @Nonnull
            @Override
            public ItemStack insertItem(int slot, @Nonnull ItemStack stack, boolean simulate) {
            	return super.insertItem(slot, stack, simulate);
            }
        };
   }

 

It seems to me that this has something to do with the block's inventory.

 

I have a few questions because this is very new and I don't know much about it:

How do you check the item in one of the slots?

How do you set what that item is?

How do you change the size of that slot?

 

I have been trying time and time again to figure out the answer to these questions with no luck. Thanks for any help.

Link to comment
Share on other sites

3 hours ago, diesieben07 said:

If you need to interact with the IItemHandler directly I would recommend also storing the IItemHandler in a field directly. The interaction through getCapability is only really necessary for interactions with other mods / automation. For accessing your own mods inventories you can use something simpler / more direct.

 

IItemHandler#getStackInSlot.

 

Since you are using ItemStackHandler you have access to the IItemHandlerModifiable interface and you can use IItemHandlerModifiable#setStackInSlot. For a plain IItemHandler you'd first have to clear the slot using IItemHandler#extractItem and then use IItemHandler#insertItem.

 

You can override ItemStackHandler#getSlotLimit.

Do you know anywhere I can get some example code / documentation implementing this? I have been taking java classes and minecraft modding has been proving a challenge

Link to comment
Share on other sites

12 hours ago, Kenneth201998 said:

Do you know anywhere I can get some example code / documentation implementing this? I have been taking java classes and minecraft modding has been proving a challenge

Get stack

Insert item

Set stack (probably not clean code, however; looking at it made me wonder if I could have written it better)

Extract item

Get slot limit

Apparently I'm a complete and utter jerk and come to this forum just like to make fun of people, be confrontational, and make your personal life miserable.  If you think this is the case, JUST REPORT ME.  Otherwise you're just going to get reported when you reply to my posts and point it out, because odds are, I was trying to be nice.

 

Exception: If you do not understand Java, I WILL NOT HELP YOU and your thread will get locked.

 

DO NOT PM ME WITH PROBLEMS. No help will be given.

Link to comment
Share on other sites

I made some changes and now have a problem opening the gui again and it says there is a mapping missing. It said it is at the line : "return super.write(tag)" 

package com.log_cabin_blocks.objects.blocks.utility_blocks.cooking_utilities.cabin_furnace;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

import com.log_cabin_blocks.objects.blocks.BlockList;

import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.inventory.container.Container;
import net.minecraft.inventory.container.INamedContainerProvider;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Items;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.Direction;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.StringTextComponent;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.util.INBTSerializable;
import net.minecraftforge.common.util.LazyOptional;
import net.minecraftforge.items.CapabilityItemHandler;
import net.minecraftforge.items.IItemHandler;
import net.minecraftforge.items.ItemStackHandler;

public class CabinFurnaceTileEntity extends TileEntity implements INamedContainerProvider {
	
	private LazyOptional<IItemHandler> handler = LazyOptional.of(this::createHandler);
    
	public CabinFurnaceTileEntity() {
		super(BlockList.cabin_furnace_tile_entity);
	}
	@SuppressWarnings("unchecked")
	@Override
	public void read(CompoundNBT tag) {
		CompoundNBT invTag = tag.getCompound("inv");
        handler.ifPresent(h -> ((INBTSerializable<CompoundNBT>) h).deserializeNBT(invTag));
        super.read(tag);
	}
	@SuppressWarnings("unchecked")
	@Override
	public CompoundNBT write(CompoundNBT tag) {
		handler.ifPresent(h -> {
            CompoundNBT compound = ((INBTSerializable<CompoundNBT>) h).serializeNBT();
            tag.put("inv", compound);
        });
		return super.write(tag);
	}
	
	private IItemHandler createHandler() {
        return new ItemStackHandler(3) {
            @Override
            protected void onContentsChanged(int slot) {
                markDirty();
            }
            @Override
            public boolean isItemValid(int slot, @Nonnull ItemStack stack) {
                return stack.getItem() == Items.DIAMOND;
            }

            @Nonnull
            @Override
            public ItemStack insertItem(int slot, @Nonnull ItemStack stack, boolean simulate) {
                if (stack.getItem() != Items.DIAMOND) {
                    return stack;
                }
                return super.insertItem(slot, stack, simulate);
            }
        };
    }
	@Override
	public Container createMenu(int p_createMenu_1_, PlayerInventory p_createMenu_2_, PlayerEntity p_createMenu_3_) {
		return new CabinFurnaceContainer(p_createMenu_1_, pos, p_createMenu_2_, p_createMenu_3_);
	}
	@Override
	public ITextComponent getDisplayName() {
		return new StringTextComponent("cabinfurnace");
	}
	@Nonnull
    @Override
    public <T> LazyOptional<T> getCapability(@Nonnull Capability<T> cap, @Nullable Direction side) {
        if (cap == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY) {
            return handler.cast();
        }
        return super.getCapability(cap, side);
    }
}

 

Error

 

[m[36m[10:17:44] [Server thread/DEBUG] [ne.mi.fm.FMLWorldPersistenceHook/WP]: Gathering id map for writing to world save Test Area 029
[m[33m[10:17:44] [Server thread/WARN] [minecraft/MinecraftServer]: Can't keep up! Is the server overloaded? Running 3870ms or 77 ticks behind
[m[32m[10:17:49] [Client thread/INFO] [minecraft/AdvancementList]: Loaded 2 advancements
[m[1;31m[10:18:00] [Server thread/FATAL] [minecraft/ThreadTaskExecutor]: Error executing task on Server
java.lang.UnsupportedOperationException: Unable to construct this menu by type
	at net.minecraft.inventory.container.Container.getType(Container.java:52) ~[?:?] {re:classloading}
	at net.minecraftforge.fml.network.NetworkHooks.openGui(NetworkHooks.java:189) ~[?:?] {re:classloading}
	at net.minecraftforge.fml.network.NetworkHooks.openGui(NetworkHooks.java:154) ~[?:?] {re:classloading}
	at com.log_cabin_blocks.objects.blocks.utility_blocks.cooking_utilities.cabin_furnace.CabinFurnace.onBlockActivated(CabinFurnace.java:69) ~[?:?] {re:classloading}
	at net.minecraft.block.BlockState.onBlockActivated(BlockState.java:296) ~[?:?] {re:classloading}
	at net.minecraft.server.management.PlayerInteractionManager.func_219441_a(PlayerInteractionManager.java:332) ~[?:?] {re:classloading}
	at net.minecraft.network.play.ServerPlayNetHandler.processTryUseItemOnBlock(ServerPlayNetHandler.java:870) ~[?:?] {re:classloading}
	at net.minecraft.network.play.client.CPlayerTryUseItemOnBlockPacket.processPacket(CPlayerTryUseItemOnBlockPacket.java:42) ~[?:?] {re:classloading}
	at net.minecraft.network.play.client.CPlayerTryUseItemOnBlockPacket.processPacket(CPlayerTryUseItemOnBlockPacket.java:12) ~[?:?] {re:classloading}
	at net.minecraft.network.PacketThreadUtil.lambda$checkThreadAndEnqueue$0(PacketThreadUtil.java:19) ~[?:?] {re:classloading}
	at net.minecraft.util.concurrent.TickDelayedTask.run(TickDelayedTask.java:20) ~[?:?] {re:classloading}
	at net.minecraft.util.concurrent.ThreadTaskExecutor.run(ThreadTaskExecutor.java:140) [?:?] {re:classloading,pl:accesstransformer:B}
	at net.minecraft.util.concurrent.RecursiveEventLoop.run(RecursiveEventLoop.java:22) [?:?] {re:classloading}
	at net.minecraft.util.concurrent.ThreadTaskExecutor.driveOne(ThreadTaskExecutor.java:110) [?:?] {re:classloading,pl:accesstransformer:B}
	at net.minecraft.server.MinecraftServer.func_213205_aW(MinecraftServer.java:726) [?:?] {re:classloading,pl:accesstransformer:B}
	at net.minecraft.server.MinecraftServer.driveOne(MinecraftServer.java:720) [?:?] {re:classloading,pl:accesstransformer:B}
	at net.minecraft.util.concurrent.ThreadTaskExecutor.driveUntil(ThreadTaskExecutor.java:123) [?:?] {re:classloading,pl:accesstransformer:B}
	at net.minecraft.server.MinecraftServer.runScheduledTasks(MinecraftServer.java:706) [?:?] {re:classloading,pl:accesstransformer:B}
	at net.minecraft.server.MinecraftServer.run(MinecraftServer.java:650) [?:?] {re:classloading,pl:accesstransformer:B}
	at java.lang.Thread.run(Unknown Source) [?:1.8.0_201] {}
[m[1;31m[10:18:00] [Server thread/FATAL] [minecraft/ThreadTaskExecutor]: Error executing task on Server
java.lang.UnsupportedOperationException: Unable to construct this menu by type
	at net.minecraft.inventory.container.Container.getType(Container.java:52) ~[?:?] {re:classloading}
	at net.minecraftforge.fml.network.NetworkHooks.openGui(NetworkHooks.java:189) ~[?:?] {re:classloading}
	at net.minecraftforge.fml.network.NetworkHooks.openGui(NetworkHooks.java:154) ~[?:?] {re:classloading}
	at com.log_cabin_blocks.objects.blocks.utility_blocks.cooking_utilities.cabin_furnace.CabinFurnace.onBlockActivated(CabinFurnace.java:69) ~[?:?] {re:classloading}
	at net.minecraft.block.BlockState.onBlockActivated(BlockState.java:296) ~[?:?] {re:classloading}
	at net.minecraft.server.management.PlayerInteractionManager.func_219441_a(PlayerInteractionManager.java:332) ~[?:?] {re:classloading}
	at net.minecraft.network.play.ServerPlayNetHandler.processTryUseItemOnBlock(ServerPlayNetHandler.java:870) ~[?:?] {re:classloading}
	at net.minecraft.network.play.client.CPlayerTryUseItemOnBlockPacket.processPacket(CPlayerTryUseItemOnBlockPacket.java:42) ~[?:?] {re:classloading}
	at net.minecraft.network.play.client.CPlayerTryUseItemOnBlockPacket.processPacket(CPlayerTryUseItemOnBlockPacket.java:12) ~[?:?] {re:classloading}
	at net.minecraft.network.PacketThreadUtil.lambda$checkThreadAndEnqueue$0(PacketThreadUtil.java:19) ~[?:?] {re:classloading}
	at net.minecraft.util.concurrent.TickDelayedTask.run(TickDelayedTask.java:20) ~[?:?] {re:classloading}
	at net.minecraft.util.concurrent.ThreadTaskExecutor.run(ThreadTaskExecutor.java:140) [?:?] {re:classloading,pl:accesstransformer:B}
	at net.minecraft.util.concurrent.RecursiveEventLoop.run(RecursiveEventLoop.java:22) [?:?] {re:classloading}
	at net.minecraft.util.concurrent.ThreadTaskExecutor.driveOne(ThreadTaskExecutor.java:110) [?:?] {re:classloading,pl:accesstransformer:B}
	at net.minecraft.server.MinecraftServer.func_213205_aW(MinecraftServer.java:726) [?:?] {re:classloading,pl:accesstransformer:B}
	at net.minecraft.server.MinecraftServer.driveOne(MinecraftServer.java:720) [?:?] {re:classloading,pl:accesstransformer:B}
	at net.minecraft.util.concurrent.ThreadTaskExecutor.driveUntil(ThreadTaskExecutor.java:123) [?:?] {re:classloading,pl:accesstransformer:B}
	at net.minecraft.server.MinecraftServer.runScheduledTasks(MinecraftServer.java:706) [?:?] {re:classloading,pl:accesstransformer:B}
	at net.minecraft.server.MinecraftServer.run(MinecraftServer.java:650) [?:?] {re:classloading,pl:accesstransformer:B}
	at java.lang.Thread.run(Unknown Source) [?:1.8.0_201] {}
[m[32m[10:18:01] [Server thread/INFO] [minecraft/IntegratedServer]: Saving and pausing game...
[m[32m[10:18:01] [Server thread/INFO] [minecraft/MinecraftServer]: Saving chunks for level 'Test Area 029'/minecraft:overworld
[m[1;31m[10:18:01] [Server thread/ERROR] [minecraft/Chunk]: A TileEntity type com.log_cabin_blocks.objects.blocks.utility_blocks.cooking_utilities.cabin_furnace.CabinFurnaceTileEntity has thrown an exception trying to write state. It will not persist, Report this to the mod author
java.lang.RuntimeException: class com.log_cabin_blocks.objects.blocks.utility_blocks.cooking_utilities.cabin_furnace.CabinFurnaceTileEntity is missing a mapping! This is a bug!
	at net.minecraft.tileentity.TileEntity.writeInternal(TileEntity.java:72) ~[?:?] {re:classloading}
	at net.minecraft.tileentity.TileEntity.write(TileEntity.java:66) ~[?:?] {re:classloading}
	at com.log_cabin_blocks.objects.blocks.utility_blocks.cooking_utilities.cabin_furnace.CabinFurnaceTileEntity.write(CabinFurnaceTileEntity.java:47) ~[?:?] {re:classloading}
	at net.minecraft.world.chunk.Chunk.func_223134_j(Chunk.java:444) ~[?:?] {re:classloading}
	at net.minecraft.world.chunk.storage.ChunkSerializer.write(ChunkSerializer.java:303) ~[?:?] {re:classloading}
	at net.minecraft.world.server.ChunkManager.func_219229_a(ChunkManager.java:677) ~[?:?] {re:classloading}
	at net.minecraft.world.server.ChunkManager.lambda$save$9(ChunkManager.java:352) ~[?:?] {re:classloading}
	at java.util.stream.ForEachOps$ForEachOp$OfRef.accept(Unknown Source) [?:1.8.0_201] {}
	at java.util.stream.ReferencePipeline$2$1.accept(Unknown Source) [?:1.8.0_201] {}
	at java.util.Iterator.forEachRemaining(Unknown Source) [?:1.8.0_201] {}
	at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Unknown Source) [?:1.8.0_201] {}
	at java.util.stream.AbstractPipeline.copyInto(Unknown Source) [?:1.8.0_201] {}
	at java.util.stream.AbstractPipeline.wrapAndCopyInto(Unknown Source) [?:1.8.0_201] {}
	at java.util.stream.ForEachOps$ForEachOp.evaluateSequential(Unknown Source) [?:1.8.0_201] {}
	at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(Unknown Source) [?:1.8.0_201] {}
	at java.util.stream.AbstractPipeline.evaluate(Unknown Source) [?:1.8.0_201] {}
	at java.util.stream.ReferencePipeline.forEach(Unknown Source) [?:1.8.0_201] {}
	at net.minecraft.world.server.ChunkManager.save(ChunkManager.java:349) [?:?] {re:classloading}
	at net.minecraft.world.server.ServerChunkProvider.save(ServerChunkProvider.java:309) [?:?] {re:classloading,pl:accesstransformer:B}
	at net.minecraft.world.server.ServerWorld.save(ServerWorld.java:770) [?:?] {re:classloading}
	at net.minecraft.server.MinecraftServer.save(MinecraftServer.java:528) [?:?] {re:classloading,pl:accesstransformer:B}
	at net.minecraft.server.integrated.IntegratedServer.tick(IntegratedServer.java:113) [?:?] {re:classloading,pl:runtimedistcleaner:A}
	at net.minecraft.server.MinecraftServer.run(MinecraftServer.java:646) [?:?] {re:classloading,pl:accesstransformer:B}
	at java.lang.Thread.run(Unknown Source) [?:1.8.0_201] {}
[m[36m[10:18:02] [Server thread/DEBUG] [ne.mi.fm.FMLWorldPersistenceHook/WP]: Gathering id map for writing to world save Test Area 029
[m[32m[10:18:10] [Server thread/INFO] [minecraft/IntegratedServer]: Saving and pausing game...
[m[32m[10:18:10] [Server thread/INFO] [minecraft/MinecraftServer]: Saving chunks for level 'Test Area 029'/minecraft:overworld
[m[36m[10:18:10] [Server thread/DEBUG] [ne.mi.fm.FMLWorldPersistenceHook/WP]: Gathering id map for writing to world save Test Area 029
[m[32m[10:18:10] [Server thread/INFO] [minecraft/ServerPlayNetHandler]: Dev lost connection: Disconnected
[m[32m[10:18:10] [Server thread/INFO] [minecraft/MinecraftServer]: Dev left the game
[m[32m[10:18:10] [Server thread/INFO] [minecraft/ServerPlayNetHandler]: Stopping singleplayer server as player logged out
[m[32m[10:18:10] [Server thread/INFO] [minecraft/MinecraftServer]: Stopping server
[m[32m[10:18:10] [Server thread/INFO] [minecraft/MinecraftServer]: Saving players
[m[32m[10:18:10] [Server thread/INFO] [minecraft/MinecraftServer]: Saving worlds
[m[32m[10:18:10] [Server thread/INFO] [minecraft/MinecraftServer]: Saving chunks for level 'Test Area 029'/minecraft:overworld
[m[32m[10:18:11] [Server thread/INFO] [minecraft/ChunkManager]: ThreadedAnvilChunkStorage (Test Area 029): All chunks are saved
[m[36m[10:18:11] [Server thread/DEBUG] [ne.mi.fm.FMLWorldPersistenceHook/WP]: Gathering id map for writing to world save Test Area 029
[m[32m[10:18:11] [Server thread/INFO] [minecraft/ChunkManager]: ThreadedAnvilChunkStorage (Test Area 029): All chunks are saved
[m[32m[10:18:11] [Client thread/INFO] [minecraft/Minecraft]: Stopping!
[m

 

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Unfortunately, your content contains terms that we do not allow. Please edit your content to remove the highlighted words below.
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

By using this site, you agree to our Terms of Use.