Back to Snippets

Custom Item Snippet.

A full custom item setup for Fabric mods using the Minecraft Java API. Covers the item class, registration, tooltip, and a right-click use action. Everything is named generically so you can drop it straight into your own mod.

How to Use?
Create the item class file, register it in your ModItems class, and add the translation key to your en_us.json lang file. Swap yourmod with your actual mod ID throughout.

Requirements
Fabric API, Minecraft 1.20+, Java 17+.

package com.yourmod.item;

import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.tooltip.TooltipType;
import net.minecraft.text.Text;
import net.minecraft.util.Hand;
import net.minecraft.util.TypedActionResult;
import net.minecraft.world.World;

import java.util.List;

public class ExampleItem extends Item {

    public ExampleItem(Settings settings) {
        super(settings);
    }

    // Right-click action
    @Override
    public TypedActionResult<ItemStack> use(
            World world, PlayerEntity player, Hand hand) {

        ItemStack stack = player.getStackInHand(hand);

        if (!world.isClient) {
            // Your custom logic here
            player.sendMessage(
                Text.literal("You used an Example Item!"), true
            );
            // Consume one item if not in creative
            if (!player.isCreative()) {
                stack.decrement(1);
            }
        }

        return TypedActionResult.success(stack);
    }

    // Custom tooltip
    @Override
    public void appendTooltip(
            ItemStack stack, TooltipContext context,
            List<Text> tooltip, TooltipType type) {

        tooltip.add(Text.literal("This is an example item.")
            .formatted(net.minecraft.util.Formatting.GRAY));
        tooltip.add(Text.literal("You can add custom logic here.")
            .formatted(net.minecraft.util.Formatting.DARK_PURPLE));
    }
}