Помогите [Решено] Проблема с поддержкой нескольких языков

Статус
Закрыто для дальнейших ответов.

Вова Петренко

Активный участник
Пользователь
Баллы
61
Имя в Minecraft
Baraban4ik
Я хочу сделать несколько языков в плагине проблема что при перезагрузки конфига язык остается тем же что и был а если сервер перезагрузить он меняется
Код:
package me.sp3ctr0.ecolobby;

import me.sp3ctr0.ecolobby.commands.EcoLobbyCommand;
import me.sp3ctr0.ecolobby.configurations.Configurations;
import me.sp3ctr0.ecolobby.event.EcoEventHandler;
import me.sp3ctr0.ecolobby.utils.Chat;
import me.sp3ctr0.ecolobby.utils.Events;
import org.bukkit.plugin.java.JavaPlugin;

import java.util.Arrays;
import java.util.List;

public final class EcoLobby extends JavaPlugin {

    private Configurations configurations = new Configurations(this, "config.yml", "lang/en.yml", "lang/ru.yml");
    private final Chat chat = new Chat(configurations);
    private final Events events = new Events(configurations);
    public final List<String> ENABLE_MESSAGE = Arrays.asList
            (
                    "§7=-=-=-=-§a§lEco§f§lLobby§7-=-=-=-=",
                    "",
                    " Version: §a" + this.getDescription().getVersion(),
                    " Author: §aSp3ctr0",
                    "",
                    "§7=-=-=-=-§a§lEco§f§lLobby§7-=-=-=-="
            );

    @Override
    public void onEnable() {
        ENABLE_MESSAGE.forEach(System.out::println);

        configurations.loadConfigurations();
        getServer().getPluginCommand("ecolobby").setExecutor(new EcoLobbyCommand(configurations, this));
        getServer().getPluginManager().registerEvents(new EcoEventHandler(configurations), this);
        Events.setRules();
    }

    @Override
    public void onDisable() {
        configurations = null;
    }

    public void reload() {
        configurations.reloadConfigurations();
    }
}
Код:
package me.sp3ctr0.ecolobby.commands;

import me.sp3ctr0.ecolobby.EcoLobby;
import me.sp3ctr0.ecolobby.configurations.Configurations;
import me.sp3ctr0.ecolobby.utils.Chat;
import me.sp3ctr0.ecolobby.utils.Events;
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 java.util.Arrays;
import java.util.List;

public class EcoLobbyCommand implements CommandExecutor {
    private final EcoLobby plugin;
    private final FileConfiguration m;
    private final FileConfiguration c;

    public EcoLobbyCommand(Configurations configurations, EcoLobby plugin) {
        this.plugin = plugin;
        c = configurations.get("config.yml");
        m = configurations.get("lang/"+ c.get("lang") +".yml");
    }
    private static final List<String> HELP = Arrays.asList
            (
                    "      &7&m=-=-=-=-&a&lEco&f&lLobby&7&m-=-=-=-=",
                    "",
                    "  /ecolobby reload &8- &aReload plugin.",
                    "   /ecolobby setspawn &8- &aSet spawn.",
                    " /ecolobby spawn &8- &aTeleport to spawn.",
                    "",
                    "      &7&m=-=-=-=-&a&lEco&f&lLobby&7&m-=-=-=-="
            );

    @Override
    public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
        if (args.length == 1 && args[0].equalsIgnoreCase("reload")) {
            if (!sender.hasPermission("ecolobby.reload")) {
                Chat.sendMessagePrefix(sender, m.getString("no-permission", "You don't have permission!"));
                return true;
            }
            Chat.sendMessagePrefix(sender, m.getString("plugin-reloaded", "Plugin successfully reloaded!"));
            plugin.reload();
        }
        else if (args.length == 1 && args[0].equalsIgnoreCase("setspawn")) {
            if (!(sender instanceof Player)) {
                Chat.sendMessagePrefix(sender, m.getString("no-player", "This command is only available to players!"));
                return true;
            }
            if (!sender.hasPermission("ecolobby.setspawn")) {
                Chat.sendMessagePrefix(sender, m.getString("no-permission", "You don't have permission!"));
                return true;
            }
            Player player = (Player) sender;
            Events.getLocation(player);

            Chat.sendMessagePrefix(sender, m.getString("successfully-setspawn", "Spawn has been successfully installed."));
        }
        else if ((args.length == 1 && args[0].equalsIgnoreCase("spawn"))) {
            if (!(sender instanceof Player)) {
                Chat.sendMessagePrefix(sender, m.getString("no-player", "This command is only available to players!"));
                return true;
            }
            if (!sender.hasPermission("ecolobby.spawn")) {
                Chat.sendMessagePrefix(sender, m.getString("no-permission", "You don't have permission!"));
                return true;
            }
            Player player = (Player) sender;
            Events.tpSpawn(player);

            Chat.sendMessagePrefix(sender, m.getString("successfully-spawn", "You have been teleported to spawn."));
        }
        else {
            if (!sender.hasPermission("ecolobby.help"))
            {
                Chat.sendMessagePrefix(sender, m.getString("no-permissions", "You don't have permission!"));
                return true;
            }
            List<String> help = m.getStringList("help");
            if (help.isEmpty()) {
                HELP.forEach((x) -> Chat.sendMessage(sender, x));
                return true;
            }
            help.forEach((x) -> Chat.sendMessage(sender, x));
        }
        return true;
    }
}
 
скинь метод которым перезагружаешь конфиг и сам конфиг
 
вот но проблема скоресего не в нём когда был только один язык всё работало нормально
Код:
package me.sp3ctr0.ecolobby.configurations;

import java.io.File;
import java.io.IOException;
import java.util.*;

import com.google.common.collect.Lists;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.Plugin;

public class Configurations
{
    private Map<String, Map.Entry<FileConfiguration, File>> configurations = new HashMap<> ();

    private List<String> configurationsNames;

    private final Plugin plugin;

    public Configurations(Plugin plugin, String... configurationsNames)
    {
        this.plugin = plugin;

        this.configurationsNames = Lists.newArrayList(configurationsNames);

        this.loadConfigurations();
    }


    private File generateDefaultFile(String name)
    {
        File file = new File(this.plugin.getDataFolder(), name);

        if (!file.exists())
        {
            this.plugin.saveResource(name, false);
        }

        return file;
    }

    public void loadConfigurations()
    {
        for (String configurationName : this.configurationsNames)
        {
            if (this.configurations.containsKey(configurationName))
            {
                continue;
            }

            File configurationFile = this.generateDefaultFile(configurationName);

            FileConfiguration configuration = YamlConfiguration.loadConfiguration(configurationFile);

            this.configurations.put(configurationName, new AbstractMap.SimpleEntry<> (configuration, configurationFile));
        }
    }

    public void reloadConfigurations()
    {
        this.configurations.clear();

        this.loadConfigurations();
    }

    private Optional<Map.Entry<FileConfiguration, File>> getEntry(String configurationName)
    {
        return Optional.ofNullable(this.configurations.get(configurationName));
    }

    public FileConfiguration get(String configurationName)
    {
        return this.getEntry(configurationName)
                .map(Map.Entry::getKey)
                .orElse(null);
    }

    private File getFile(String configurationName)
    {
        return this.getEntry(configurationName)
                .map(Map.Entry::getValue)
                .orElse(null);
    }


    public FileConfiguration save(FileConfiguration fileConfiguration, String s) {
        try {
            fileConfiguration.save(new File(plugin.getDataFolder(), s));
        } catch (IOException var3) {
            var3.printStackTrace();
        }
        return fileConfiguration;
    }
}
 
сам конфиг бессмысленно скидывать там всё я проверял путь правильный и тд
 
думаю дело в том что ты когда регистрируешь команду в конструкторе EcoLobbyCommand то у тебя объекты конфига создаются один раз, а потом не изменяются. Т.е вот ты скинул своему обработчику команд Configurations объект, и после команды reload перезагружаешь тот объект что в твоем классе EcoLobby, а не тот что в EcoLobbyCommand, кроме того ты в конструкторе завязываешь файлы конфига и языка, в итоге даже при перезагрузке они не изменяться. Чтобы это все поправить, можешь сделать так чтобы объект Configurations был только в классе EcoLobby, а не передавался обработчику команд, потом этот объект получать через plugin.getConfigurations() например. Чтобы перезагрузить твои поля m и c в обработчике, сделай метод который будет заново их инициализировать
 
Типа сделать в классе EcoLobby метод getConfigurations() и в нём их типа получать
 
можешь мне с этим а то не очень понимаю как это сделать
 
можешь мне с этим а то не очень понимаю как это сделать
в EcoLobby добавь метод
public Configurations getConfigurations() {
return this.configurations;
}

в EcoLobbyCommand убери все из конструктора кроме plugin, и добавь метод
private void loadConfigs() {
c = plugin.getConfigurations().get("config.yml");
m = plugin.getConfigurations().get("lang/"+ c.get("lang") +".yml");
}
и при команде reload сначала сделай plugin.reload(); а потом loadConfigs();
 
а это а что то менять в обработчике ивентов там просто было также как в команде
 
типа того или нет
Код:
public class EcoEventHandler implements Listener {
    private final EcoLobby plugin;
    private FileConfiguration m;
    private FileConfiguration c;

    public EcoEventHandler(EcoLobby plugin) {
        this.plugin = plugin;
    }
    private void loadConfigs() {
        FileConfiguration c = plugin.getConfigurations().get("config.yml");
        m = plugin.getConfigurations().get("lang/"+ c.get("main.lang") +".yml");
    }
 
типа того или нет
Код:
public class EcoEventHandler implements Listener {
    private final EcoLobby plugin;
    private FileConfiguration m;
    private FileConfiguration c;

    public EcoEventHandler(EcoLobby plugin) {
        this.plugin = plugin;
    }
    private void loadConfigs() {
        FileConfiguration c = plugin.getConfigurations().get("config.yml");
        m = plugin.getConfigurations().get("lang/"+ c.get("main.lang") +".yml");
    }
да
 
а метод loadConfigs нигде не надо использовать
теперь при воде команды появляется ошибка и ссылается туда где получаю строку из фала перевода
 
Вот
83 строка
m.getString("no-permission", "You don't have permission!"));
Код:
[23:45:39 WARN]: Unexpected exception while parsing console command "el"
org.bukkit.command.CommandException: Unhandled exception executing command 'el' in plugin EcoLobby v1.0
        at org.bukkit.command.PluginCommand.execute(PluginCommand.java:46) ~[patched_1.12.2.jar:git-Paper-1618]
        at org.bukkit.command.SimpleCommandMap.dispatch(SimpleCommandMap.java:152) ~[patched_1.12.2.jar:git-Paper-1618]
        at org.bukkit.craftbukkit.v1_12_R1.CraftServer.dispatchCommand(CraftServer.java:685) ~[patched_1.12.2.jar:git-Paper-1618]
        at org.bukkit.craftbukkit.v1_12_R1.CraftServer.dispatchServerCommand(CraftServer.java:648) ~[patched_1.12.2.jar:git-Paper-1618]
        at net.minecraft.server.v1_12_R1.DedicatedServer.aP(DedicatedServer.java:463) ~[patched_1.12.2.jar:git-Paper-1618]
        at net.minecraft.server.v1_12_R1.DedicatedServer.D(DedicatedServer.java:424) ~[patched_1.12.2.jar:git-Paper-1618]
        at net.minecraft.server.v1_12_R1.MinecraftServer.C(MinecraftServer.java:774) ~[patched_1.12.2.jar:git-Paper-1618]
        at net.minecraft.server.v1_12_R1.MinecraftServer.run(MinecraftServer.java:666) ~[patched_1.12.2.jar:git-Paper-1618]
        at java.lang.Thread.run(Thread.java:834) [?:?]
Caused by: java.lang.NullPointerException
        at me.sp3ctr0.ecolobby.commands.EcoLobbyCommand.onCommand(EcoLobbyCommand.java:83) ~[?:?]
        at org.bukkit.command.PluginCommand.execute(PluginCommand.java:44) ~[patched_1.12.2.jar:git-Paper-1618]
        ... 8 more
 
забыл сказать loadConfigs добавь в конструктор, а то у тебя переменные не инициализированы
 
Код:
    public EcoLobbyCommand(EcoLobby plugin) {
        this.plugin = plugin;
        loadConfigs();
    }
 
да и в обработчике событий также
 
Статус
Закрыто для дальнейших ответов.
Назад
Верх