Creating GUI with Config Section

Discussion in 'Spigot Plugin Development' started by DarkKnights22, Oct 8, 2019.

Thread Status:
Not open for further replies.
  1. Code (Java):

         
    try {
        Inventory previewGUI = Bukkit.createInventory(null, 9, Chat.colorRaw("&cKit Preview"));
        KitManager manager = new KitManager();

        for (String k : plugin.getConfig().getConfigurationSection("Kits").getKeys(false)) {
            manager.loadFromConfig(plugin.getConfig().getConfigurationSection("Kits." + k + "."));
            for (int i = 0; i < 7; i++) {
                for (String s : manager.getItems()) {
                    ItemStack item = ItemCreator.create(null,null, Material.valueOf(s), false, 1);
                    previewGUI.setItem(i, item);
                    i++;
                }
            }
        }

        p.openInventory(previewGUI);
    } catch (NullPointerException ex) {
        ex.printStackTrace();
    }
     
    This is how I try to open a player's inventory. For each item in the kit, I want to display it in the preview GUI.
    The KitManager class just gets the objects from the config
     
  2. You shouldn't keep getting your config for everything, it can be an impact on server performance if you're doing over and over. I haven't tried your code but whats the issue?
     
  3. The preview gui kit does not show up.
     
  4. is there an error? Also show your ItemCreator class. You also aren't loading any information in from the config so what is it creating?
     
  5. Not significantly. The file is only read from disk the first time you call JavaPlugin#getConfig. The next calls will just return the existing instance (source).

    That's not necessarily true. Their KitManager class seems to be extracting a bunch of Material names from the ConfigurationSection it's given.

    Have you made sure the code actually gets run?
    If it gets run and the inventory does not get opened, then you should be seeing the stacktrace.


    There's a bunch of general issues with your code.

    What does the KitManager class do exactly? If you're going to parse your items there, you might as well get the actual ItemStacks.

    Why are you using an ItemCreator class if you could trivially just do new ItemStack(material)?

    What is this trying to do exactly?:
    Code (Java):
            for (int i = 0; i < 7; i++) {
                for (String s : manager.getItems()) {
                    ItemStack item = ItemCreator.create(null,null, Material.valueOf(s), false, 1);
                    previewGUI.setItem(i, item);
                    i++;
                }
            }
    What's the first loop for exactly? It loops until i<7, but that depends on how many objects you iterate through in the inner loop. If the inner loop is run 7 or more times, the outer loop gets run once, if the inner loop is run less than 7 times, the other loop is run until such a time at which the size of the container (or array) + i is less than 7. In fact, every iteration of the outer loop, all but the first element set by the last array is changed to something else. So if you manager#getItems returns materials [A, B, C], you'll see items of type [A, A, A, A, A, B, C] in your preview.
     
    • Like Like x 1
  6. Oh shit lol How would I fix the iteration loop then
     
  7. If you just want to display the items (for which you get the names from KitManager#getItems), all you'd need to do is remove the first (of the two I quoted) loop and initialize the integer i as 0.

    But please, take a look at my other comments as well.
     
  8. Yeah I have. I used my ItemCreator so if I wanted to customise the item meta of the material in the future I can
     
  9. Code (Java):
    try {
                Inventory previewGUI = Bukkit.createInventory(null, 9, Chat.colorRaw("&cKit Preview"));
                KitManager manager = new KitManager();
                int i = 0;

                for (String k : plugin.getConfig().getConfigurationSection("Kits").getKeys(false)) {
                    manager.loadFromConfig(plugin.getConfig().getConfigurationSection("Kits." + k + "."));
                        for (String s : manager.getItems()) {
                            previewGUI.setItem(i, new ItemStack(Material.valueOf(s)));
                            i++;
                        }
                }

                p.openInventory(previewGUI);
            } catch (NullPointerException ex) {
                ex.printStackTrace();
            }
    Code (Java):
    } else if (e.getClick().isRightClick()) {
                        PreviewGUI.open(p, plugin);
                        e.setCancelled(true);
                    }
    Is there something I'm missing? The Preview GUI does not open?
     
  10. Did you see these questions?
    By the way, you shouldn't be catching a NullPointerException. You should be doing null-checks instead.
     
  11. Code (Java):
    Inventory previewGUI = Bukkit.createInventory(null, 9, Chat.colorRaw("&cKit Preview"));
            KitManager manager = new KitManager();
            int i = 0;

            for (String k : plugin.getConfig().getConfigurationSection("Kits").getKeys(false)) {
                manager.loadFromConfig(plugin.getConfig().getConfigurationSection("Kits." + k));
                for (String s : manager.getItems()) {
                    previewGUI.setItem(i, new ItemStack(Material.valueOf(s)));
                    i++;
                }
            }
            p.openInventory(previewGUI);
        }
    So this is my code now. When I open the normal Kit GUI, the default item is not there. No errors, and the config is fresh. The default item is supposed to be there, and on right clicking it, you open the preview GUI.
     
  12. You're going to have to be more precise?
    What is this "normal Kit GUI"? I've got a feeling it's another inventory that you've not shared with us. If there's an issue there, there's no way for anyone to help you unless you share your code.

    If you're iterating over a config and something is different than what you'd expect, your best case is some debug output. Just output the key(s) and/or value(s) you're reading from the config to see what they actually are.

    And again, you've hidden some of your config parsing in another class. I have no way of knowing what that class does?
    On another note, what does your actual config look like? Perhaps what you're trying to do is read a list instead of a ConfigurationSection?
     
  13. KitManager:
    Code (Java):
    public class KitManager {
        private Map<UUID, Long> map = new HashMap<>(); // Store who has received the kit and the date
        private String name;
        private boolean firework;
        private String particle;
        private String sound;
        private String message;
        private String permission;
        private List<String> lore;
        private String material;
        private List<String> commands;
        private List<String> items;
        private int cooldown;

        public void loadFromConfig(ConfigurationSection section) {
            name = section.getString("Name");
            message = section.getString("Message");
            permission = section.getString("Permission");
            lore = section.getStringList("Lore");
            commands = section.getStringList("Commands");
            firework = section.getBoolean("Firework");
            particle = section.getString("Particle");
            material = section.getString("Material");
            sound = section.getString("Sound");
            items = section.getStringList("Items");
            cooldown = section.getInt("Cooldown");
        }

        public String getTitle() {
            return Chat.colorRaw(name);
        }

        public boolean getFirework() {
            return firework;
        }

        public String getParticle() {
            return particle;
        }

        public String getSound() {
            return sound;
        }

        public String getMessage() {
            return Chat.colorRaw(message).replace("%kit%", getTitle());
        }

        public String getPermission() {
            return permission;
        }

        public List<String> getLore() {
            return lore;
        }

        public String getMaterial() {
            return material;
        }

        public List<String> getCommands() {
            return commands;
        }

        public List<String> getItems() {
            return items;
        }

        public int getCooldown() {
            return cooldown;
        }


        public Map<UUID, Long> getCooldownMap() {
            return map;
        }

    }
    InventoryClickEvent Listener for normal GUI:
    Code (Java):
    @EventHandler
        public void onClick(InventoryClickEvent e) {
            Player p = (Player) e.getWhoClicked();
            try {

            if (e.getView().getTitle().equals(Chat.colorRaw("&a&lInfinityPvPKits GUI"))) {
                if (e.getCurrentItem() == null || e.getCurrentItem().getItemMeta() == null || e.getCurrentItem().getItemMeta().getDisplayName() == null) {
                    return;
                }
                    if (e.getClick().isLeftClick()) {
                        for (String k : plugin.getConfig().getConfigurationSection("Kits").getKeys(false)) {
                            if (p.isOp() || p.hasPermission(manager.getPermission())) {
                                manager.loadFromConfig(plugin.getConfig().getConfigurationSection("Kits." + k + "."));
                                KIT.put(k, manager);
                                Long last = manager.getCooldownMap().get(p.getUniqueId());
                                if (last != null) {
                                    long delta = System.currentTimeMillis() - (last + manager.getCooldown() * 50);
                                    if (delta < 0) {
                                        p.sendMessage(Chat.colorRaw("&c&l(!) &7You are still on cooldown for " + (Math.abs(delta) / 1000) + " seconds!"));
                                        e.setCancelled(true);
                                        p.closeInventory();
                                        return;
                                    }

                                }

                                for (String s : manager.getCommands()) {
                                    plugin.getServer().dispatchCommand(plugin.getServer().getConsoleSender(), Chat.colorRaw(s.replace("%player%", p.getName())));
                                }
                                for (String s : manager.getItems()) {
                                    p.getInventory().addItem(new ItemStack(Material.valueOf(s)));
                                }
                                if (manager.getFirework()) {
                                    MinigameUtils.spawnRandomFirework(p.getLocation());
                                }
                                p.playSound(p.getLocation(), Sound.valueOf(manager.getSound()), 1, 1);
                                p.playEffect(p.getLocation(), Effect.valueOf(manager.getParticle()), 1);
                                p.sendMessage(manager.getMessage());
                                manager.getCooldownMap().put(p.getUniqueId(), System.currentTimeMillis());
                            } else {
                                p.sendMessage(Chat.colorRaw("&c&l(!) &7You do not have permission!"));
                            }
                        }
                    } else if (e.getClick().isRightClick()) {
                        PreviewGUI.open(p, plugin);
                        e.setCancelled(true);
                    }
                }
            } catch (
                    NullPointerException ex) {
                ex.printStackTrace();
            }
            e.setCancelled(true);
            p.closeInventory();
        }
    Preview GUI open method:
    Code (Java):
    public static void open(Player p, InfinityPvPKits plugin) {
            Inventory previewGUI = Bukkit.createInventory(null, 9, Chat.colorRaw("&cKit Preview"));
            KitManager manager = new KitManager();
            int i = 0;

            for (String k : plugin.getConfig().getConfigurationSection("Kits").getKeys(false)) {
                manager.loadFromConfig(plugin.getConfig().getConfigurationSection("Kits." + k + "."));
                for (String s : manager.getItems()) {
                    previewGUI.setItem(i, new ItemStack(Material.valueOf(s)));
                    i++;
                }
            }
            p.openInventory(previewGUI);
        }
     
  14. Ok, so now the default item appears but when right clicking, it just closes the inventory and does not open the Preview GUI.

    The code does execute, because I added a message just after opening the Preview GUI and it worked, so it's an error in the Preview GUI class
     
  15. Did you happen to look at the javadocs of InventoryClickEvent?
    I'll quote it for you:
    It sounds to me like you're trying to use one of those methods.
     
  16. Nope, to open the inventory I do Player#openInventory(inventory)
    And to close, I do Player#closeInventory()

    And also, I don't have a click event for the Preview GUI yet..
     
  17. Please read again what I just sent you in the last message.

    Failing that, I'll make it red and bold for you this time:

    The following should never be invoked by an EventHandler for InventoryClickEvent using the HumanEntity or InventoryView associated with this event:

    To invoke one of these methods, schedule a task using BukkitScheduler.runTask(Plugin, Runnable), which will run the task on the next tick. Also be aware that this is not an exhaustive list, and other methods could potentially create issues as well.

    This is exactly what you're doing within your onClick method!
    For your information, Player extends HumanEntity(which I thought would have been obvious since you're even casting the HumanEntity to a Player).
     
Thread Status:
Not open for further replies.