Jump to content
Search In
  • More options...
Find results that contain...
Find results in...

[1.16.5] Adding a Button to KeyBindings


Recommended Posts

I was able to replace the keybindinglist with my own list but now the list isn't scollable anymore. I fixed that by using the GuiScreenEvent.MouseScrollEvent. Is there a better way of doing that?

Edited by Skyriis
Link to post
Share on other sites

Event Handler

    private static KeyBindingListReplacement replacement;

    @SubscribeEvent
    public static void onOpenGui(final GuiScreenEvent.InitGuiEvent.Post event) {
        if (!(event.getGui() instanceof ControlsScreen)) return;
        ControlsScreen controlsScreen = (ControlsScreen) event.getGui();
        replacement = new KeyBindingListReplacement(controlsScreen, event.getGui().getMinecraft());
        ObfuscationReflectionHelper.setPrivateValue(ControlsScreen.class, controlsScreen, replacement, "field_146494_r");
    }

    @SubscribeEvent
    public static void onScroll(final GuiScreenEvent.MouseScrollEvent.Pre event) {
        if (!(event.getGui() instanceof ControlsScreen)) return;
        replacement.mouseScrolled(event.getMouseX(), event.getMouseY(), event.getScrollDelta());
    }

 

Replacement:

@OnlyIn(Dist.CLIENT)
public class KeyBindingListReplacement extends KeyBindingList {
    private final ControlsScreen controlsScreen;
    private int maxListLabelWidth;

    public KeyBindingListReplacement(ControlsScreen controls, Minecraft mcIn) {
        super(controls, mcIn);
        this.controlsScreen = controls;
        this.clearEntries();

        KeyBinding[] akeybinding = ArrayUtils.clone(mcIn.gameSettings.keyBindings);
        Arrays.sort(akeybinding);
        String lastCategory = null;

        for (KeyBinding keybinding : akeybinding) {
            String keyCategory = keybinding.getKeyCategory();
            if (!keyCategory.equals(lastCategory)) {
                lastCategory = keyCategory;
                this.addEntry(new KeyBindingList.CategoryEntry(new TranslationTextComponent(keyCategory)));
            }

            ITextComponent itextcomponent = new TranslationTextComponent(keybinding.getKeyDescription());
            int i = mcIn.fontRenderer.getStringPropertyWidth(itextcomponent);
            if (i > this.maxListLabelWidth) {
                this.maxListLabelWidth = i;
            }

            this.addEntry(new KeyEntry(keybinding, itextcomponent));
        }
    }

 

Link to post
Share on other sites

That worked.

 

Here is my solution

@SubscribeEvent
    public static void onOpenGui(final GuiScreenEvent.InitGuiEvent.Post event) {
        if (!(event.getGui() instanceof ControlsScreen)) return;

        final ControlsScreen controlsScreen = (ControlsScreen) event.getGui();
        final KeyBindingList replacement = new KeyBindingListReplacement(controlsScreen, event.getGui().getMinecraft());
        final KeyBindingList old = ObfuscationReflectionHelper.getPrivateValue(ControlsScreen.class, controlsScreen, "field_146494_r");

        controlsScreen.getEventListeners().remove(old);

        ObfuscationReflectionHelper.setPrivateValue(ControlsScreen.class, controlsScreen, replacement, "field_146494_r");

        try {
            Method addChildMethod = ObfuscationReflectionHelper.findMethod(Screen.class, "func_230481_d_", IGuiEventListener.class);
            addChildMethod.setAccessible(true);
            addChildMethod.invoke(controlsScreen, replacement);
            addChildMethod.setAccessible(false);
        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }

 

Link to post
Share on other sites

That is not how you should handle exceptions.

And there is no reason to call setAccessible(true) when using ObfuscationReflectionHelper.

And callign setAccessible(false) when you never use the Method again afterwards also doesn't do anything.

Link to post
Share on other sites
2 hours ago, diesieben07 said:

That is not how you should handle exceptions

I'll work on that :)

2 hours ago, diesieben07 said:

And there is no reason to call setAccessible(true) when using ObfuscationReflectionHelper.

And callign setAccessible(false) when you never use the Method again afterwards also doesn't do anything

Thanks. I'll remove those lines.

Link to post
Share on other sites

Now the added Button (btnSyncToCloud) isn't clickable but hoverable.

All other buttons are clickable and work how the should.

 

Changed KeyBindingListReplacement.KeyEntry.class

@OnlyIn(Dist.CLIENT)
    public class KeyEntryReplacement extends KeyBindingList.Entry {
        /**
         * The keybinding specified for this KeyEntry
         */
        private final KeyBinding keybinding;
        /**
         * The localized key description for this KeyEntry
         */
        private final ITextComponent keyDesc;
        private final Button btnChangeKeyBinding;
        private final Button btnReset;
        private final IconButton btnSyncToCloud;

        private KeyEntryReplacement(final KeyBinding keyBinding, final ITextComponent description) {
            this.keybinding = keyBinding;
            this.keyDesc = description;

            this.btnChangeKeyBinding = new Button(0, 0, 75 + 20, 20, description, (p_214386_2_) -> KeyBindingListReplacement.this.controlsScreen.buttonId = keyBinding) {
                protected IFormattableTextComponent getNarrationMessage() {
                    return keyBinding.isInvalid() ? new TranslationTextComponent("narrator.controls.unbound", description) : new TranslationTextComponent("narrator.controls.bound", description, super.getNarrationMessage());
                }
            };

            this.btnReset = new Button(0, 0, 50, 20, new TranslationTextComponent("controls.reset"), (p_214387_2_) -> {
                keybinding.setToDefault();
                KeyBindingListReplacement.this.minecraft.gameSettings.setKeyBindingCode(keyBinding, keyBinding.getDefault());
                KeyBinding.resetKeyBindingArrayAndHash();
            }) {
                protected IFormattableTextComponent getNarrationMessage() {
                    return new TranslationTextComponent("narrator.controls.reset", description);
                }
            };
            
            this.btnSyncToCloud = new IconButton("cloud", (button) -> SyncHandler.addToSyncList(this.keybinding)) {
                @Override
                protected IFormattableTextComponent getNarrationMessage() {
                    return new TranslationTextComponent("belovedkeybindings.buttons.upload_to_cloud", description);
                }
            };
        }

        @Override
        public void render(MatrixStack matrixStack, int p_230432_2_, int renderPosY, int renderPosX, int p_230432_5_, int p_230432_6_, int mouseX, int mouseY, boolean p_230432_9_, float particalTicks) {...}

        public List<? extends IGuiEventListener> getEventListeners() {
            return ImmutableList.of(this.btnChangeKeyBinding, this.btnReset, this.btnSyncToCloud);
        }

        @Override
        public boolean mouseClicked(double mouseX, double mouseY, int button) {
            return this.btnChangeKeyBinding.mouseClicked(mouseX, mouseY, button) || this.btnReset.mouseClicked(mouseX, mouseY, button) || this.btnSyncToCloud.mouseClicked(mouseX, mouseY, button);
        }

        @Override
        public boolean mouseReleased(double mouseX, double mouseY, int button) {
            return this.btnChangeKeyBinding.mouseReleased(mouseX, mouseY, button) || this.btnReset.mouseReleased(mouseX, mouseY, button) || this.btnSyncToCloud.mouseReleased(mouseX, mouseY, button);
        }
    }

 

IconButton.class

@OnlyIn(Dist.CLIENT)
public class IconButton extends ImageButton {
    private final ResourceLocation resourceLocation;
    private final int yOffset = 128;

    public IconButton(String iconName, IPressable onPressIn) {
        super(0, 0, 20, 20, 0, 0, 128, new ResourceLocation(BelovedKeybindings.MODID, "textures/icons/" + iconName + ".png"), onPressIn);
        this.resourceLocation = new ResourceLocation(BelovedKeybindings.MODID, "textures/icons/" + iconName + ".png");
    }

    @Override
    public void renderButton(MatrixStack matrixStack, int mouseX, int mouseY, float partialTicks) {
        Minecraft minecraft = Minecraft.getInstance();
        minecraft.getTextureManager().bindTexture(this.resourceLocation);
        int i = 0;
        if (this.isMouseOver(mouseX, mouseY)) {
            i += yOffset;
        }

        RenderSystem.disableDepthTest();
        blit(matrixStack, this.x, this.y, 16, 16, 0, i, 128, 128, 256, 256);
        RenderSystem.enableDepthTest();

        if (this.isMouseOver(mouseX, mouseY)) {
            this.renderToolTip(matrixStack, mouseX, mouseY);
        }
    }

    @Override
    public void renderToolTip(MatrixStack matrixStack, int mouseX, int mouseY) {
        super.renderToolTip(matrixStack, mouseX, mouseY);
        Minecraft.getInstance().fontRenderer.drawStringWithShadow(matrixStack, getNarrationMessage().getString(), mouseX + 8, mouseY, Color.WHITE.getRGB());
    }
}

 

Any ideas how to fix that?

Edited by Skyriis
Link to post
Share on other sites

I more or less found the problem.

There is a event listender on the left side of the screen which was blocking the button.

I just moved the button to another place because i could not find the listender.

Now everything works like it should.

Link to post
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.

Guest
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.



  • Recently Browsing

    No registered users viewing this page.

  • Posts

    • My build.gradle:  buildscript { repositories { maven { url = 'https://files.minecraftforge.net/maven' } mavenCentral() jcenter() } dependencies { classpath group: 'net.minecraftforge.gradle', name: 'ForgeGradle', version: '4.1.+', changing: true } } plugins { id 'com.github.johnrengelman.shadow' version '6.1.0' } apply plugin: 'net.minecraftforge.gradle' // Only edit below this line, the above code adds and enables the necessary things for Forge to be setup. apply plugin: 'eclipse' apply plugin: 'maven-publish' version = '1.0' group = 'com.tatuck.coordinateslocator' // http://maven.apache.org/guides/mini/guide-naming-conventions.html archivesBaseName = 'tatuckcoordslocator' java.toolchain.languageVersion = JavaLanguageVersion.of(8) // Mojang ships Java 8 to end users, so your mod should target Java 8. println('Java: ' + System.getProperty('java.version') + ' JVM: ' + System.getProperty('java.vm.version') + '(' + System.getProperty('java.vendor') + ') Arch: ' + System.getProperty('os.arch')) minecraft { mappings channel: 'official', version: '1.16.5' runs { client { workingDirectory project.file('run') property 'forge.logging.markers', 'REGISTRIES' property 'forge.logging.console.level', 'debug' mods { examplemod { source sourceSets.main } } } server { workingDirectory project.file('run/server') property 'forge.logging.markers', 'REGISTRIES' property 'forge.logging.console.level', 'debug' mods { examplemod { source sourceSets.main } } setForceExit(false) } data { workingDirectory project.file('run') property 'forge.logging.markers', 'REGISTRIES' property 'forge.logging.console.level', 'debug' args '--mod', 'examplemod', '--all', '--output', file('src/generated/resources/'), '--existing', file('src/main/resources/') mods { examplemod { source sourceSets.main } } } } } // Include resources generated by data generators. sourceSets.main.resources { srcDir 'src/generated/resources' } dependencies { minecraft 'net.minecraftforge:forge:1.16.5-36.1.0' compile 'org.mongodb:mongodb-driver-sync:4.2.3' shadow 'org.mongodb:mongodb-driver-sync:4.2.3' shadow 'org.mongodb:bson:4.2.3' // http://www.gradle.org/docs/current/userguide/artifact_dependencies_tutorial.html // http://www.gradle.org/docs/current/userguide/dependency_management.html } // Example for how to get properties into the manifest for reading by the runtime.. jar { manifest { attributes([ "Specification-Title": "examplemod", "Specification-Vendor": "examplemodsareus", "Specification-Version": "1", // We are version 1 of ourselves "Implementation-Title": project.name, "Implementation-Version": "${version}", "Implementation-Vendor" :"examplemodsareus", "Implementation-Timestamp": new Date().format("yyyy-MM-dd'T'HH:mm:ssZ") ]) } } // Example configuration to allow publishing using the maven-publish task // This is the preferred method to reobfuscate your jar file jar.finalizedBy('reobfJar') // However if you are in a multi-project build, dev time needs unobfed jar files, so you can delay the obfuscation until publishing by doing //publish.dependsOn('reobfJar') publishing { publications { mavenJava(MavenPublication) { artifact jar } } repositories { maven { url "file:///${project.projectDir}/mcmodsrepo" } } } shadowJar { configurations = [project.configurations.shadow] } reobf { shadowJar {} }   Update:  I have tried again and now it is showing me this error: Description: mouseClicked event handler java.lang.NoSuchMethodError: net.minecraft.client.Minecraft.getInstance()Lnet/minecraft/client/Minecraft; at com.tatuck.coordinateslocator.TatuckCoordinatesLocator.onSound(TatuckCoordinatesLocator.java:43) ~[?:1.0] {re:classloading} at net.minecraftforge.eventbus.ASMEventHandler_0_TatuckCoordinatesLocator_onSound_PlaySoundEvent.invoke(.dynamic) ~[?:?] {} at net.minecraftforge.eventbus.ASMEventHandler.invoke(ASMEventHandler.java:85) ~[eventbus-4.0.0.jar:?] {} at net.minecraftforge.eventbus.EventBus$$Lambda$2544/1439945495.invoke(Unknown Source) ~[?:?] {} at net.minecraftforge.eventbus.EventBus.post(EventBus.java:302) ~[eventbus-4.0.0.jar:?] {} at net.minecraftforge.eventbus.EventBus.post(EventBus.java:283) ~[eventbus-4.0.0.jar:?] {} at net.minecraftforge.client.ForgeHooksClient.playSound(ForgeHooksClient.java:282) ~[?:?] {re:classloading} at net.minecraft.client.audio.SoundEngine.func_148611_c(SoundEngine.java:271) ~[?:?] {re:classloading,pl:accesstransformer:B,pl:runtimedistcleaner:A} at net.minecraft.client.audio.SoundHandler.func_147682_a(SoundHandler.java:136) ~[?:?] {re:classloading,pl:runtimedistcleaner:A} at net.minecraft.client.gui.widget.Widget.func_230988_a_(Widget.java:198) ~[?:?] {re:classloading,pl:runtimedistcleaner:A} at net.minecraft.client.gui.widget.Widget.func_231044_a_(Widget.java:135) ~[?:?] {re:classloading,pl:runtimedistcleaner:A} at net.minecraft.client.gui.INestedGuiEventHandler.func_231044_a_(SourceFile:27) ~[?:?] {re:classloading} at net.minecraft.client.gui.screen.MainMenuScreen.func_231044_a_(MainMenuScreen.java:288) ~[?:?] {re:classloading,pl:runtimedistcleaner:A} at net.minecraft.client.MouseHelper.func_198033_b(MouseHelper.java:87) ~[?:?] {re:classloading,pl:runtimedistcleaner:A} at net.minecraft.client.MouseHelper$$Lambda$3917/1046211253.run(Unknown Source) ~[?:?] {} at net.minecraft.client.gui.screen.Screen.func_231153_a_(Screen.java:427) ~[?:?] {re:classloading,pl:runtimedistcleaner:A} at net.minecraft.client.MouseHelper.func_198023_a(MouseHelper.java:85) ~[?:?] {re:classloading,pl:runtimedistcleaner:A} at net.minecraft.client.MouseHelper.func_228030_c_(MouseHelper.java:175) ~[?:?] {re:classloading,pl:runtimedistcleaner:A} at net.minecraft.client.MouseHelper$$Lambda$3916/2087758561.run(Unknown Source) ~[?:?] {} at net.minecraft.util.concurrent.ThreadTaskExecutor.execute(SourceFile:94) ~[?:?] {re:classloading,pl:accesstransformer:B} at net.minecraft.client.MouseHelper.func_228028_b_(MouseHelper.java:174) ~[?:?] {re:classloading,pl:runtimedistcleaner:A} at net.minecraft.client.MouseHelper$$Lambda$3530/1682774881.invoke(Unknown Source) ~[?:?] {} at org.lwjgl.glfw.GLFWMouseButtonCallbackI.callback(GLFWMouseButtonCallbackI.java:36) ~[lwjgl-glfw-3.2.2.jar:build 10] {} at org.lwjgl.system.JNI.invokeV(Native Method) ~[lwjgl-3.2.2.jar:build 10] {} at org.lwjgl.glfw.GLFW.glfwWaitEventsTimeout(GLFW.java:3174) ~[lwjgl-glfw-3.2.2.jar:build 10] {} at com.mojang.blaze3d.systems.RenderSystem.limitDisplayFPS(SourceFile:127) ~[?:?] {re:classloading} at net.minecraft.client.Minecraft.func_195542_b(Minecraft.java:999) [?:?] {re:classloading,pl:accesstransformer:B,pl:runtimedistcleaner:A} at net.minecraft.client.Minecraft.func_99999_d(Minecraft.java:607) [?:?] {re:classloading,pl:accesstransformer:B,pl:runtimedistcleaner:A} at net.minecraft.client.main.Main.main(Main.java:184) [?:?] {re:classloading,pl:runtimedistcleaner:A} at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.8.0_51] {} at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[?:1.8.0_51] {} at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.8.0_51] {} at java.lang.reflect.Method.invoke(Method.java:497) ~[?:1.8.0_51] {} at net.minecraftforge.fml.loading.FMLClientLaunchProvider.lambda$launchService$0(FMLClientLaunchProvider.java:51) [forge-1.16.5-36.1.0.jar:36.1] {} at net.minecraftforge.fml.loading.FMLClientLaunchProvider$$Lambda$438/1260043537.call(Unknown Source) [forge-1.16.5-36.1.0.jar:36.1] {} at cpw.mods.modlauncher.LaunchServiceHandlerDecorator.launch(LaunchServiceHandlerDecorator.java:37) [modlauncher-8.0.9.jar:?] {} at cpw.mods.modlauncher.LaunchServiceHandler.launch(LaunchServiceHandler.java:54) [modlauncher-8.0.9.jar:?] {} at cpw.mods.modlauncher.LaunchServiceHandler.launch(LaunchServiceHandler.java:72) [modlauncher-8.0.9.jar:?] {} at cpw.mods.modlauncher.Launcher.run(Launcher.java:82) [modlauncher-8.0.9.jar:?] {} at cpw.mods.modlauncher.Launcher.main(Launcher.java:66) [modlauncher-8.0.9.jar:?] {}  
    • Im working on a mod, but i dont know how i can make crops in Minecraft 1.16.Can somebody help me by making for example a tutorial?
    • I have tried but for some reason Minecraft doesn't detect the compiled mod. I don't think it is giving me an error because I have checked the logs but I found nothing.
    • https://mcforge.readthedocs.io/en/latest/networking/simpleimpl/#the-version-checker
  • Topics

  • Who's Online (See full list)

×
×
  • Create New...

Important Information

By using this site, you agree to our Privacy Policy.