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 WebsiteCadiboo.github.io

My ModsCadiboo.github.io/projects

My TutorialsCadiboo.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

    • So I've read the EULA, and lets be straight...     If I split my modpack(of my mods, yeah I'm nuts) into several(many) individual mods(like just one boss) with minor additions(plus not working together), then have a complete/modpack version on patreon/onlyfans having each addon work together... Would people buy my idea?
    • German A1 – C1, TestDAF, Goethe B1, B2, C1, C2, valid GOETHE certificate German A1 – C1, TestDAF, Goethe B1, B2, C1, C2, valid GOETHE certificate(+27(838-80-8170
    • Done, it still crashed. New log https://paste.ee/p/kYv6e
    • I am migrating a mod from 1.16.5 to 1.20.2 The version for 1.16.5 can be found here https://github.com/beothorn/automataCraft For the block called automata_start, it uses TileEntities and has blockstates, model/block and textures on json files. This is currently working fine on 1.16.5 https://github.com/beothorn/automataCraft/tree/master/src/main/resources/assets/automata For 1.20.2 I migrated the logic from TileEntities to BlockEntity. The mod is working fine. All blocks and Items are working with the correct textures except for the textures for each state of the automata_start block. No changes where made to the json files. This is the branch I am working on (there were some refactorings, but all is basically the same): https://github.com/beothorn/automataCraft/tree/1_20/src/main/resources/assets/automata The only difference I can think that may be related is that i had to implement createBlockStateDefinition on the BaseEntityBlock: https://github.com/beothorn/automataCraft/blob/1_20/src/main/java/br/com/isageek/automata/automata/AutomataStartBlock.java#L43 This is driving me crazy. I know the jsons are being loaded as I put a breakpoint at `net.minecraft.client.resources.model.ModelBakery#loadModel` and I can see BlockModelDefinition.fromJsonElement being called with automata_start. I also printed the state from the arguments of the tick function call and they look correct (https://github.com/beothorn/automataCraft/blob/1_20/src/main/java/br/com/isageek/automata/automata/Ticker.java#L32 ): blockState Block{automata:automata_start}[state=loadreplaceables] In game, all I see is the no textures. I think it is weird it is not the "missing texture" texture so I think it may be related to the material, but I had no success tweaking it (https://github.com/beothorn/automataCraft/blob/1_20/src/main/java/br/com/isageek/automata/automata/AutomataStartBlock.java#L37).   public static final Property<AutomataStartState> state = EnumProperty.create("state", AutomataStartState.class); private final AtomicReference<RegistryObject<BlockEntityType<?>>> blockEntityType; private final Map<String, RegistryObject<Block>> registeredBlocks; public AutomataStartBlock( final AtomicReference<RegistryObject<BlockEntityType<?>>> blockEntityType, final Map<String, RegistryObject<Block>> registeredBlocks ) { super(BlockBehaviour.Properties.of().mapColor(MapColor.STONE).strength(1.5F, 6.0F)); this.blockEntityType = blockEntityType; this.registeredBlocks = registeredBlocks; this.registerDefaultState(this.getStateDefinition().any().setValue(state, AutomataStartState.LOAD_REPLACEABLES)); } @Override protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> stateBuilder) { stateBuilder.add(state); }     So my cry for help is, anyone has any ideas? Is there a way to easily debug this, for example somewhere where I can list the textures for a given state, or make sure this is loaded?   Thanks in advance for the hints
    • FAILURE: Build failed with an exception. * What went wrong: A problem occurred configuring root project 'forge-1.8.9-11.15.1.2318-1.8.9-mdk'. > Could not resolve all dependencies for configuration ':classpath'. > Could not resolve net.minecraftforge.gradle:ForgeGradle:2.1-SNAPSHOT. Required by: :forge-1.8.9-11.15.1.2318-1.8.9-mdk:unspecified > Could not resolve net.minecraftforge.gradle:ForgeGradle:2.1-SNAPSHOT. > Unable to load Maven meta-data from https://jcenter.bintray.com/net/minecraftforge/gradle/ForgeGradle/2.1-SNAPSHOT/maven-metadata.xml. > Could not GET 'https://jcenter.bintray.com/net/minecraftforge/gradle/ForgeGradle/2.1-SNAPSHOT/maven-metadata.xml'. > peer not authenticated > Could not resolve net.minecraftforge.gradle:ForgeGradle:2.1-SNAPSHOT. > Unable to load Maven meta-data from http://files.minecraftforge.net/maven/net/minecraftforge/gradle/ForgeGradle/2.1-SNAPSHOT/maven-metadata.xml. > Could not GET 'http://files.minecraftforge.net/maven/net/minecraftforge/gradle/ForgeGradle/2.1-SNAPSHOT/maven-metadata.xml'. > peer not authenticated * Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. BUILD FAILED Total time: 2.78 secs This is the error I got. Any help would be appreciated!
  • Topics

×
×
  • Create New...

Important Information

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