Reloading Config from Another Class

Discussion in 'Plugin Development' started by TheMinecraftKnight, Feb 22, 2017.

Thread Status:
Not open for further replies.
  1. Hey, all. I'm trying to make a GUI plugin, but I'm having a bit of a problem: reloading the config file from another class. Before you give me loads of other forum threads, I've looked at a large amount of them already, and they don't seem to be working. Here are my class files:

    Code:
    package com.knightzmc.staffgui;
    
    import java.io.File;
    import java.util.List;
    
    import org.bukkit.Bukkit;
    import org.bukkit.Material;
    import org.bukkit.configuration.file.FileConfiguration;
    import org.bukkit.inventory.Inventory;
    import org.bukkit.inventory.ItemStack;
    import org.bukkit.inventory.meta.ItemMeta;
    import org.bukkit.plugin.Plugin;
    import org.bukkit.plugin.java.JavaPlugin;
    import net.milkbowl.vault.chat.Chat;
    import net.milkbowl.vault.economy.Economy;
    import net.milkbowl.vault.permission.Permission;
    
    public class StaffMenu extends JavaPlugin {
        public static Economy econ;
        public static Permission perms;
        public static Chat chat;
        public static Plugin plugin;
        public FileConfiguration config;
        public File configFile;
        public void onEnable() {
            plugin = this;
            FileConfiguration config = this.getConfig();
            config.options().copyDefaults(true);
            saveConfig();
            getCommand("staffmenu").setExecutor(new StaffGui());
            getCommand("sm").setExecutor(new StaffGui());
            Bukkit.getPluginManager().registerEvents(new GuiListener(), this);
        }
    
        public static void createDisplay(Material material, Inventory inv, int Slot, String name, List<String> lore) {
            ItemStack item = new ItemStack(material);
            ItemMeta meta = item.getItemMeta();
            meta.setDisplayName(name);
            meta.setLore(lore);
            item.setItemMeta(meta);
            inv.setItem(Slot, item);
        }
    
        public static StaffMenu getPlugin() {
            return StaffMenu.getPlugin(StaffMenu.class);
        }
    }
    
    Code:
    package com.knightzmc.staffgui;
    
    import java.util.logging.Logger;
    
    import org.bukkit.Bukkit;
    import org.bukkit.command.Command;
    import org.bukkit.command.CommandExecutor;
    import org.bukkit.command.CommandSender;
    import org.bukkit.configuration.file.FileConfiguration;
    import org.bukkit.entity.Player;
    import org.bukkit.inventory.Inventory;
    import org.bukkit.plugin.Plugin;
    
    import net.md_5.bungee.api.ChatColor;
    
    public class StaffGui implements CommandExecutor {
    
        private static Logger log = Logger.getLogger("Minecraft");
        static String bold = ChatColor.BOLD + "";
        static String red = ChatColor.RED + "";
        static String gold = ChatColor.GOLD + "";
        static String aqua = ChatColor.AQUA + "";
        static String darkaqua = ChatColor.DARK_AQUA + "";
        static String green = ChatColor.GREEN + "";
        static String darkgreen = ChatColor.DARK_GREEN + "";
        static String strikethrough = ChatColor.STRIKETHROUGH + "";
        static String italic = ChatColor.ITALIC + "";
        static String underline = ChatColor.UNDERLINE + "";
        static String darkred = ChatColor.DARK_RED + "";
        static String yellow = ChatColor.YELLOW + "";
        static Plugin plugin = StaffMenu.getPlugin();
        static FileConfiguration config = StaffMenu.getPlugin().getConfig();
        public static Inventory staffMenu = Bukkit.createInventory(null, 9,
                ChatColor.valueOf(config.getString("maincolor")) + bold + "Staff Menu");
    
        public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
            if (!(sender instanceof Player)) {
                log.info("You really think that a console can open a GUI? Only players can use this command");
                return true;
            }
            Player player = (Player) sender;
            if (cmd.getName().equalsIgnoreCase("staffmenu") || cmd.getName().equalsIgnoreCase("sm")) {
                if (args.length == 1) {
                    if (args[0].equals("reload")) {
                        if (player.hasPermission("staffmenu.reload")) {
                            plugin.reloadConfig();
                            sender.sendMessage(green + "Config Reloaded!");
                        } else
                            sender.sendMessage(red + "No permission!");
                    } else {
                        sender.sendMessage(green + "Usage: " + gold + "/staffmenu [reload]");
                    }
                } else {
                    if (player.hasPermission("staffmenu.open")) {
    
                        player.openInventory(staffMenu);
                    } else {
                        player.sendMessage(red + "I'm pretty sure you're not staff.");
                    }
                }
            }
            return false;
        }
    }
    
    I don't think you really need the GUI Listener class, do you?
    Thanks for any help!
     
    Last edited by a moderator: Feb 22, 2017
  2. Offline

    timtower Administrator Administrator Moderator

    @TheMinecraftKnight Please don't use public static, you don't need it for plugins. Certainly not in that amount.
    Don't use the Minecraft logger.
    Pass the main instance along to the listeners / executors using the constructor.
     
  3. Offline

    MrGeneralQ


    Hello sir


    What you are looking for is called a Constructor.


    For ex:

    You got a class called OnCommand and your Main class is called

    In order to access stuff on your main class you need something we call A constructor.
    Even though this is basic Java knowledge I will try to explain you.


    A constructor always uses the name of the classs and has the Parameter in it of the instance you are trying to get data from.

    For ex:
    Code:
    public class OnCommand()
    {
    
    
    }
    This is just our empty OnCommand Class. Now we are going to create the constructor to get data from it.

    Code:
    public class OnCommand()
    {
    public OnCommand(Main main)
    {
    
    }
    }
    see any links? Main main just represents an instance of the Main class. Now we need to make it so our class can access that variable. We therefore create an empty variable of the type Main.

    Code:
    public class OnCommand()
    {
    
    private final Main main;
    
    public OnCommand(Main main)
    {
    
    }
    }
    Now the final part to this is that we give the instance from the constructor to our variable. We do that like this.

    Code:
    public class OnCommand()
    private final Main main;
    
    public OnCommand(Main main)
    {
       this.main = main;
    }
    }
    This: is refering to THIS class which has a variable on top called main.


    If we use colors then it's easy to see the links between them.



    public class OnCommand()
    {
    private final Main main;

    public OnCommand(Main main)
    {
    this.main = main;
    }
    }

    The colours should explain it. Now since we created our constructor has a Paramater main, you have to feed it with the main parameter if you initialize the OnCommand() class.

    getCommand("myCommand").setExecutor(new OnCommand(this),this);

    This was a very very detailed explenation, now it's up to you to make work of it and understand. Good luck!
     
    Last edited: Feb 22, 2017
  4. Okay, I've done all that, and I'm doing main.reloadConfig(); and it still isn't working. What would I actually do to reload it?
     
  5. Offline

    MrGeneralQ

    In that case post me both your classes please. Your main and your other class. I'll take a look at it.
     
  6. Thanks :)
    Main Class:
    Code:
    package com.knightzmc.staffgui;
    
    import java.util.List;
    
    import org.bukkit.Bukkit;
    import org.bukkit.Material;
    import org.bukkit.configuration.file.FileConfiguration;
    import org.bukkit.inventory.Inventory;
    import org.bukkit.inventory.ItemStack;
    import org.bukkit.inventory.meta.ItemMeta;
    import org.bukkit.plugin.java.JavaPlugin;
    
    import net.milkbowl.vault.chat.Chat;
    import net.milkbowl.vault.economy.Economy;
    import net.milkbowl.vault.permission.Permission;
    
    public class StaffMenu extends JavaPlugin {
        Economy econ;
        Permission perms;
        Chat chat;
        FileConfiguration config;
        public static StaffMenu plugin;
        public void onEnable() {
            plugin = this;
            FileConfiguration config = plugin.getConfig();
            config.options().copyDefaults(true);
            saveConfig();
            getCommand("staffmenu").setExecutor(new StaffGui(this));
            getCommand("sm").setExecutor(new StaffGui(this));
            Bukkit.getPluginManager().registerEvents(new GuiListener(), this);
        }
        public void onDisable() {
            plugin = null;
        }
    
        public static void createDisplay(Material material, Inventory inv, int Slot, String name, List<String> lore) {
            ItemStack item = new ItemStack(material);
            ItemMeta meta = item.getItemMeta();
            meta.setDisplayName(name);
            meta.setLore(lore);
            item.setItemMeta(meta);
            inv.setItem(Slot, item);
        }
    
        public static StaffMenu getPlugin() {
            return StaffMenu.getPlugin(StaffMenu.class);
        }
    
    }
    
    CommandExecutor Class:
    Code:
    package com.knightzmc.staffgui;
    
    import java.util.logging.Logger;
    
    import org.bukkit.Bukkit;
    import org.bukkit.command.Command;
    import org.bukkit.command.CommandExecutor;
    import org.bukkit.command.CommandSender;
    import org.bukkit.configuration.file.FileConfiguration;
    import org.bukkit.entity.Player;
    import org.bukkit.inventory.Inventory;
    import org.bukkit.plugin.Plugin;
    
    import net.md_5.bungee.api.ChatColor;
    
    public class StaffGui implements CommandExecutor {
        private static Logger log = Logger.getLogger("Minecraft");
        static String bold = ChatColor.BOLD + "";
        String red = ChatColor.RED + "";
        String gold = ChatColor.GOLD + "";
        String aqua = ChatColor.AQUA + "";
        String darkaqua = ChatColor.DARK_AQUA + "";
        String green = ChatColor.GREEN + "";
        String darkgreen = ChatColor.DARK_GREEN + "";
        String strikethrough = ChatColor.STRIKETHROUGH + "";
        String italic = ChatColor.ITALIC + "";
        String underline = ChatColor.UNDERLINE + "";
        String darkred = ChatColor.DARK_RED + "";
        String yellow = ChatColor.YELLOW + "";
        Plugin plugin = StaffMenu.getPlugin();
        private final StaffMenu main;
        public StaffGui(StaffMenu main)
        {
        this.main = main;
        }
        static FileConfiguration config = StaffMenu.plugin.getConfig();
        public static Inventory staffMenu = Bukkit.createInventory(null, 9,
                ChatColor.valueOf(config.getString("maincolor")) + bold + "Staff Menu");
    
        public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
            if (!(sender instanceof Player)) {
                log.info("You really think that a console can open a GUI? Only players can use this command");
                return true;
            }
            Player player = (Player) sender;
            if (cmd.getName().equalsIgnoreCase("staffmenu") || cmd.getName().equalsIgnoreCase("sm")) {
                if (args.length == 1) {
                    if (args[0].equals("reload")) {
                        if (player.hasPermission("staffmenu.reload")) {
                            main.reloadConfig();
                            sender.sendMessage(green + "Config Reloaded!");
                        } else
                            sender.sendMessage(red + "No permission!");
                    } else {
                        sender.sendMessage(green + "Usage: " + gold + "/staffmenu [reload]");
                    }
                } else {
                    if (player.hasPermission("staffmenu.open")) {
    
                        player.openInventory(staffMenu);
                    } else {
                        player.sendMessage(red + "I'm pretty sure you're not staff.");
                    }
                }
            }
            return false;
        }
    }
    
     
  7. Offline

    MrGeneralQ

    There is no constructor in there?

    OTHER NOTE: remove those "statics" and use the correct ChatColor import. Use the one from Bukkit.
     
  8. Offline

    timtower Administrator Administrator Moderator

    Code:
    public StaffGui(StaffMenu main)
    {
    this.main = main;
    }
    There is.
     
  9. Offline

    MrGeneralQ

    ah yes , @TheMinecraftKnight my bad.

    Well do you have any errors now?

    @timtower sorry for the double post, I couldn't insert Quotes without a new post. Could you merge them?

    @TheMinecraftKnight

    replace all that with 1 line saveDefaultConfig();

    remove that , that's useless

    remove

    use the correct ChatColor import

    remove that.


    Bassicly remove ALL static statements

    EDIT by Moderator: merged posts, please use the edit button instead of double posting.
     
    Last edited by a moderator: Feb 22, 2017
  10. Nope. When I type /sm reload it doesn't reload at all, it just tells me "Config Reloaded!"
     
  11. Offline

    MrGeneralQ

    Try to stop your server first. Then export the new code with the stuff I told you. Then change something in the config and use the reload command.

    Your constructor is setup correctly.
     
  12. Offline

    timtower Administrator Administrator Moderator

  13. Doing that now. I'm pretty sure FileConfiguration config = StaffMenu.plugin.getConfig(); has to be static because I need to access it from another class
    Nevermind
     
  14. Offline

    MrGeneralQ

    No... That's why you created a constructor. Don't use static please.
     
  15. Okay, I'm having another problem now:
    Code:
        public Inventory staffMenu = Bukkit.createInventory(null, 9,
                ChatColor.valueOf(config.getString("maincolor")) + bold + "Staff Menu");
    
    I can't access it from another class with
    Code:
    Inventory staffMenu = StaffGui.staffMenu;
    It says I can't make a static reference to a non-static even though the piece of code it's in isn't static.
     
  16. Offline

    MrGeneralQ

    Same thing. You are trying to use StaffGui (which is the class)

    Create a constructor with a parameter of

    Small reminder:

    private final StaffGui guiClass;
    public yourClassName(StaffGui guiClass)
    {
    this.guiClass = guiClass;
    }
     
  17. Offline

    timtower Administrator Administrator Moderator

    @TheMinecraftKnight Make a getter for it. Make sure the main class has an instance of the staffGui class.
    And register /sm as alias, not as its own command.
     
  18. I guess guiClass is the class I'm trying to get the gui into, and yourClassName is the main class?
     
  19. Offline

    timtower Administrator Administrator Moderator

  20. Offline

    MrGeneralQ

    @timtower I know.

    @TheMinecraftKnight

    You create the constructor in the class where you want to use data.

    GuiClass is the class you want to get data FROM.
    Look at the reminder
     
  21. Offline

    timtower Administrator Administrator Moderator

  22. Okay. I've put this in GuiListener:
    Code:
        private final StaffGui StaffGui;
    
        public GuiListener(StaffGui StaffGui) {
            this.StaffGui = StaffGui;
        }
        Inventory staffMenu = StaffGui.staffMenu;
    
    But it says "The Blank Final field StaffGui may not have been initalized"
     
  23. Offline

    timtower Administrator Administrator Moderator

  24. Offline

    MrGeneralQ

    like @timtower said:

    now create in the StaffGui a method "getGui()"

    this returns the staffGui variable. And then you're good to go
     
  25. But what type of variable should it be? staffGui is a class file?
     
  26. Offline

    timtower Administrator Administrator Moderator

    @TheMinecraftKnight Don't start variable names with upper case letters please. It makes your code very hard to read and the chance that you make a mistake using them very big.

    Which variable do you need where? Where does it come from?
     
  27. Offline

    MrGeneralQ


    in your StaffGui create a method getGui();

    Code:
    public Inventory getGui()
    {
    return this.staffMenu;
    }
    Now in your other class simly call the method.

    Inventory myGui = guiClass.getGui();

    guiClass: this is the variable you created before, NOT the className!
     
  28. It still "hasn't been initalized"
     
  29. Offline

    timtower Administrator Administrator Moderator

    Post your code please.
     
  30. Offline

    MrGeneralQ

    You probably did something like this,

    Inventory staffGui;

    this will return nullPointerException;

    Inventory staffGui = main.Bukkit.createInventory ....


    that's what you need.
     
Thread Status:
Not open for further replies.

Share This Page