Skip to content

Developer Sub Command

ludgart edited this page Nov 11, 2020 · 1 revision

Developer Sub Command

Create an new Java Class. Example TestInfoCommand

Extend and Implement from our API
public class TestInfoCommand extends SubCommand {
  
  TestInfoCommand() {
    // info = our sub command
    // 0 = expected arguments
    // 1 = maximum arguments
    super("info", 0, 1);
  }

  @Override
  public String getUsage() {
    return "Wrong command usage! Type /test info <player>";
  }

  @Override
  public String getPermission() {
    return "permission.test.info";
  }

  @Override
  public void onExecute(CommandSender commandSender, String[] strings) {
  }

  @Override
  public List<String> getCompletions(CommandSender commandSender, String[] strings) {
    return null;
  }
}

Method onExecute()

In our example you get from the /test command information about yourself and from other players.

@Override
public void onExecute(CommandSender sender, String[] args) {
  // Check if only the player executed the command
  if (!(sender instanceof Player)) return;

  // Convert from the Type CommandSender to Player
  Player player = (Player) sender;

  // Check args
  if(args.length == 0) {
    player.sendMessage(TextComponent.fromLegacyText("Health: " + player.getHealth()));
    return;
  }

  if(args.length == 1) {
    // Do information for other players
    return;
  }

Register SubCommand

Go back to your TestCommand class and create at top an new List

private static final List<SubCommand> SUB_COMMANDS = new ArrayList<>();

In the constructor we need to fill the list with the SubCommand class.

Stream.of(
  new TestInfoCommand()
).forEach(SUB_COMMANDS::add);

In the onExecute() Method we need to add following code

....

for (SubCommand subCommand : SUB_COMMANDS) {
  if (subCommand.getName().equalsIgnoreCase(args[0]))
    subCommand.execute(sender, args);
}

If you added every step without problen, then you can now compile and test your new SubCommand!

Information

Server Owner

Developer

Clone this wiki locally