Jump to content

[1.12.2] Creating a Scrollbar as apart of a Custom Gui


quinn50

Recommended Posts

So I want to create scrollbar that is going to be apart of my custom storage device for my mod, which is going to sort and display items based of their NBT values so that it would be more storage efficient for the player to use. I have tried basing my code off the method that vanilla does for the creative inventory, and I am currently having a issue where when I change the size of the game window the game crashes with a null pointer exception.

ย 

Crash Log

Container Class

public class SoulChamberContainer extends Container {

  TileEntityChamber chamber;
  GuiChamber gui;
    public static TileEntityChamber chamberInv;
    public NonNullList<ItemStack> list = NonNullList.<ItemStack>create();




    public SoulChamberContainer(InventoryPlayer playerInv, final TileEntityChamber chamber){
        this.chamber = chamber;

        IItemHandler inventory = chamber.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, EnumFacing.NORTH);


        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 9; j++) {
                addSlotToContainer(new Slot(playerInv, j + i * 9 + 9, 8 + j * 18, 140 + i * 18));
            }
        }

        for (int j = 0; j < 12; ++j)
        {
            for (int k = 0; k < 4; ++k)
            {
                addSlotToContainer(new soulChamberSlot(inventory, k + j * 4, 80 + k * 18, 18 + j * 18) {
                    @Override
                    public void onSlotChanged() {
                        chamber.markDirty();
                    }
                });

            }
        }




        for (int k = 0; k < 9; k++) {
            addSlotToContainer(new Slot(playerInv, k, 8 + k * 18, 198));
        }

    }



    public void scrollTo(float pos)
    {
        int i = (this.list.size() + 9 - 1) / 9 - 5;
        int j = (int)((double)(pos * (float)i) + 0.5D);

        if (j < 0)
        {
            j = 0;
        }

        for (int k = 0; k < 5; ++k)
        {
            for (int l = 0; l < 9; ++l)
            {
                int i1 = l + (k + j) * 9;

                if (i1 >= 0 && i1 < this.list.size())
                {
                    gui.setInventorySlotContents(l + k * 9, (ItemStack) this.list.get(i1));
                }
                else
                {
                    gui.setInventorySlotContents(l + k * 9, ItemStack.EMPTY);
                }
            }
        }
    }







    public boolean moreThan1PageItems()
    {
        return this.list.size() > 24;
    }



    @Override
    public boolean canInteractWith(EntityPlayer playerIn) {
        return true;
    }


    @Override
    public ItemStack transferStackInSlot(EntityPlayer player, int index) {
        ItemStack itemstack = ItemStack.EMPTY;
        Slot slot = inventorySlots.get(index);

        if (slot != null && slot.getHasStack()) {
            ItemStack itemstack1 = slot.getStack();
            itemstack = itemstack1.copy();

                int containerSlots = inventorySlots.size() - player.inventory.mainInventory.size();

                if (index < containerSlots) {
                    if (!this.mergeItemStack(itemstack1, containerSlots, inventorySlots.size(), true)) {
                        return ItemStack.EMPTY;
                    }
                } else if (!this.mergeItemStack(itemstack1, 0, containerSlots, false)) {
                    return ItemStack.EMPTY;
                }

                if (itemstack1.getCount() == 0) {
                    slot.putStack(ItemStack.EMPTY);
                } else {
                    slot.onSlotChanged();
                }

                if (itemstack1.getCount() == itemstack.getCount()) {
                    return ItemStack.EMPTY;
                }

                slot.onTake(player, itemstack1);
            }


        return itemstack;
    }
    }





ย 

ย 

GUI Class


public class GuiChamber extends GuiContainer {
    private static final ResourceLocation BACKGROUND = new ResourceLocation(soulomancy.MODID, "textures/gui/chamber.png");

    public NonNullList<ItemStack> list = NonNullList.<ItemStack>create();


    int ScrollRow = 0;
    private boolean isScrolling = false;
    private boolean wasClicking = false;
    private float scrollCurrent;
    public static TileEntityChamber chamberInv;
    private static SoulChamberContainer chamContainer;


    private InventoryPlayer playerInv;
    public GuiChamber (Container container, InventoryPlayer playerInv) {
        super(container);
        this.playerInv = playerInv;
    }




    @Override
    public void initGui() {
        super.initGui();
        this.buttonList.add(new GuiButton(1, 100, 200, 100, 20, "Button id: 1"));
        ItemStack is;
        for (int i = 0; i < 48; ++i)
        {
            if (!(chamberInv.getStackInSlot(i) == null)) {
                is = chamberInv.getStackInSlot(i);
            }else {
                is = ItemStack.EMPTY;
            }

            if (!(is == null))
            {
                this.list.add(is);
                chamContainer.list = this.list;


            }

        }

    }

    @Override
    public void updateScreen()
    {
        super.updateScreen();
    }


    @Override
    protected void actionPerformed(GuiButton button) throws IOException {
        if (button.id == 1){
            System.out.println("Button id 1: Test");
        }
    }

    @Override
    public void drawScreen(int mouseX, int mouseY, float partialTicks) {
        this.drawDefaultBackground();
        super.drawScreen(mouseX, mouseY, partialTicks);
        this.renderHoveredToolTip(mouseX, mouseY);
      //  Slot slot
        boolean flag = Mouse.isButtonDown(0);
        int k = this.guiLeft;
        int l = this.guiTop;
        int i1 = k + 175;
        int j1 = l + 18;
        int k1 = i1 + 14;
        int l1 = j1 + 108;

        if (!this.wasClicking && flag && mouseX >= i1 && mouseY >= j1 && mouseX < k1 && mouseY < l1) {
            this.isScrolling = this.needsScrollBars();
            System.out.println("DEBUG: Scrollbar Needed");
        }

        if (!flag) {
            this.isScrolling = false;
            System.out.println("DEBUG: Not Scrolling");
        } else {


        }

        this.wasClicking = flag;

        if (this.isScrolling) {
            System.out.println("DEBUG: Is Scrolling");
            this.scrollCurrent = (mouseY - j1 - 7.5F) / (l1 - j1 - 15.0F);
            this.scrollCurrent = MathHelper.clamp(this.scrollCurrent, 0.0F, 1.0F);
            chamContainer.scrollTo(this.scrollCurrent);
        }



    }

    public void handleMouseInput() throws IOException
    {
        super.handleMouseInput();
        int i = Mouse.getEventDWheel();

        if (i != 0 && this.needsScrollBars())
        {
            int j = (((SoulChamberContainer)this.inventorySlots).list.size() + 9 - 1) / 9 - 5;

            if (i > 0)
            {
                i = 1;
            }

            if (i < 0)
            {
                i = -1;
            }

            this.scrollCurrent = (float)((double)this.scrollCurrent - (double)i / (double)j);
            this.scrollCurrent = MathHelper.clamp(this.scrollCurrent, 0.0F, 1.0F);
            ((SoulChamberContainer)this.inventorySlots).scrollTo(this.scrollCurrent);
        }
    }




    private boolean needsScrollBars()
    {
        if (((SoulChamberContainer)this.inventorySlots).moreThan1PageItems())
        {
            return false;
        }
        else
        {
           return true;
        }
    }






    public void setInventorySlotContents(int i, ItemStack itemStack)
    {
        chamberInv.invContents(i, itemStack);

        if (itemStack != null && itemStack.getCount() > 64)
        {
            itemStack.setCount(64);
        }
        chamberInv.markDirty();
    }







    @Override
    protected void drawGuiContainerBackgroundLayer(float partialTicks, int mouseX, int mouseY) {
        GlStateManager.color(1, 1, 1, 1);
        mc.getTextureManager().bindTexture(BACKGROUND);
        int x = (width - xSize) / 2;
        int y = (height - ySize) / 2;
        drawTexturedModalRect(x, y, 0, 0, xSize, 222);

        GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
        int var5 = (this.width - this.xSize) / 2;
        int var6 = (this.height - this.ySize) / 2;
        this.drawTexturedModalRect(var5, var6, 0, 0, this.xSize, this.ySize);
        int i1 = this.guiLeft + 153;
        int k = this.guiTop + 18;
        int l = k + 90;
        if (needsScrollBars())
        {
            System.out.println("Scroll Activated");
            this.drawString(mc.fontRenderer, "fart", 172, 220, 0xffffff);
            this.drawTexturedModalRect(i1, k + (int)((float)(l - k - 17) * this.scrollCurrent), 0,198, 12, 15);
        }
        else
        {
            this.drawTexturedModalRect(i1, k, 12, 198, 12, 15);

        }

    }

    @Override
    protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) {
        String name = I18n.format(ModBlocks.soulChamber.getUnlocalizedName() + ".name");
        fontRenderer.drawString(name, xSize / 2 - fontRenderer.getStringWidth(name) / 2, 6, 0x404040);
        fontRenderer.drawString(playerInv.getDisplayName().getUnformattedText(), 8, 222 - 94, 0x404040);
    }

    public int rowsVisible() {
        return 6;
    }

}

ย 

Tile Entity Classย 


public class TileEntityChamber extends TileEntity {

private ItemStackHandler inv = new ItemStackHandler(48);
    private final NonNullList<ItemStack> inventoryContents = NonNullList.withSize(48, net.minecraft.item.ItemStack.EMPTY);


        public void invContents(int i, ItemStack stack){
                this.inventoryContents.set(i, stack);

        }



        public ItemStack getStackInSlot(int i){

                  return i >= 48 ? ItemStack.EMPTY : this.inventoryContents.get(i);
        }

    @Override
    public void markDirty() {
        super.markDirty();
    }




    public ItemStackHandler getInv() {
        return inv;
    }

    @Override
    public NBTTagCompound writeToNBT(NBTTagCompound compound) {
        compound.setTag("inventory", inv.serializeNBT());
        return super.writeToNBT(compound);
    }

    @Override
    public void readFromNBT(NBTTagCompound compound) {
        inv.deserializeNBT(compound.getCompoundTag("inventory"));
        super.readFromNBT(compound);
    }

    @Override
    public boolean hasCapability(Capability<?> capability, @Nullable EnumFacing facing) {
        return capability == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY || super.hasCapability(capability, facing);
    }

    @Nullable
    @Override
    public <T> T getCapability(Capability<T> capability, @Nullable EnumFacing facing) {
        return capability == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY ? (T)inv: super.getCapability(capability, facing);
    }
}






ย 

ย 

Also I would like insight on how you would go about having only a certain amount of slots show up per "page", so like I only want 24 slots showing up but as you scroll of course new slots show up.

Link to comment
Share on other sites

Caused by: java.lang.NullPointerException

ย  ย  at com.quinn50.soulomancy.blocks.soulChamber.SoulChamberContainer.scrollTo(SoulChamberContainer.java:91) ~[SoulChamberContainer.class:?]

ย  ย  at com.quinn50.soulomancy.blocks.soulChamber.GuiChamber.handleMouseInput(GuiChamber.java:154) ~[GuiChamber.class:?]

ย  ย  at net.minecraft.client.gui.GuiScreen.handleInput(GuiScreen.java:576) ~[GuiScreen.class:?]

It might have something to do with scaled resolution? Try placing conditional breakpoints and find out what is null

Edited by Cadiboo

About Me

Spoiler

My Discordย -ย Cadiboo#8887

My Website -ย Cadiboo.github.io

My Mods -ย Cadiboo.github.io/projects

My Tutorials -ย Cadiboo.github.io/tutorials

Versions below 1.14.4ย are no longer supported on this forum.ย Use the latest version toย receive support.

When asking support remember to include all relevant log files (logs are found in .minecraft/logs/), code if applicable and screenshots if possible.

Only download mods from trusted sites like CurseForge (minecraft.curseforge.com).ย A list of bad sites can be foundย here, with more information available atย stopmodreposts.org

Edit your own signature atย www.minecraftforge.net/forum/settings/signature/ย (Make sure to check its compatibility with the Dark Theme)

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.

Announcements



  • Recently Browsing

    • No registered users viewing this page.
  • Posts

    • This has been released asย 49.0.49.
    • https://youtube.com/shorts/gqLTSMymgUg?si=5QOeSvA4TTs-bL46
    • CubeHaven is a SMP server with unique features that can't be found on the majority of other servers! Java: MC.CUBEHAVEN.NET Bedrock: MC.CUBEHAVEN.NET:19132 3 different stores: - CubeHaven Store: Our store to purchase using real money. - Bitcoin Store: Store for Bitcoin. Bitcoin can be earned from playing the server. Giving options for players if they want to spend real money or grind to obtain exclusive packages. - Black Market: A hidden store for trading that operates outside our traditional stores, like custom enchantments, exclusive items and more. Some of our features include: Rank Up: Progress through different ranks to unlock new privileges and perks. ๐Ÿ“ˆ Skills: RPG-style skill system that enhances your gaming experience! ๐ŸŽฎ Leaderboards: Compete and shine! Top players are rewarded weekly! ๐Ÿ† Random Teleporter: Travel instantly across different worlds with a click! ๐ŸŒ Custom World Generation: Beautifully generated world. ๐ŸŒ Dungeons: Explore challenging and rewarding dungeons filled with treasures and monsters. ๐Ÿฐ Kits: Unlock ranks and gain access to various kits. ๐Ÿ› ๏ธ Fishing Tournament: Compete in a friendly fishing tournament! ๐ŸŽฃ Chat Games: Enjoy games right within the chat! ๐ŸŽฒ Minions: Get some help from your loyal minions. ๐Ÿ‘ฅ Piรฑata Party: Enjoy a festive party with Piรฑatas! ๐ŸŽ‰ Quests: Over 1000 quests that you can complete! ๐Ÿ“œ Bounty Hunter: Set a bounty on a player's head. ๐Ÿ’ฐ Tags: Displayed on nametags, in the tab list, and in chat. ๐Ÿท๏ธ Coinflip: Bet with other players on coin toss outcomes, victory, or defeat! ๐ŸŸข Invisible & Glowing Frames: Hide your frames for a cleaner look or apply a glow to it for a beautiful look. ๐Ÿ”ฒโœจ[ Player Warp: Set your own warp points for other players to teleport to. ๐ŸŒŸ Display Shop: Create your own shop and sell to other players! ๐Ÿ›’ Item Skins: Customize your items with unique skins. ๐ŸŽจ Pets: Your cute loyal companion to follow you wherever you go! ๐Ÿพ Cosmetics: Enhance the look of your character with beautiful cosmetics! ๐Ÿ’„ XP-Bottle: Store your exp safely in a bottle for later use! ๐Ÿถ Chest & Inventory Sorting: Keep your items neatly sorted in your inventory or chest! ๐Ÿ“ฆ Glowing: Stand out from other players with a colorful glow! โœจ Player Particles: Over 100 unique particle effects to show off. ๐ŸŽ‡ Portable Inventories: Over virtual inventories with ease. ๐Ÿงณ And a lot more! Become part of our growing community today! Discord:ย https://cubehaven.net/discord Java: MC.CUBEHAVEN.NET Bedrock: MC.CUBEHAVEN.NET:19132
    • # Problematic frame: # C [libopenal.so+0x9fb4d] It is always the same issue - this refers to the Linux OS - so your system may prevent Java from working ย  I am not familiar with Linux - check for similar/related issues ย 
    • Create a new instance and start with Embeddium/Oculus and Valkyrien Skies Try different builds of Embeddium/Valkyrien Skies until you find a working combination - then add the rest of your mods one by one or in groups
  • Topics

×
×
  • Create New...

Important Information

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