-
Notifications
You must be signed in to change notification settings - Fork 1
Create a formatter
This is follow-up of the Create an extension page.
We need a initializer class for this, in this class the formatters will be initialized.
It will be a utility class, so only static fields / methods are going to be used.
public class ExtFormatters {
private static final IFormatterRegistry REGISTRY = IAdvancedDebug.get().getFormatterRegistry();
public static void initClass() {
}
}
The first line inside the class you will see the private REGISTRY
constant, this is used so you don't have to write by every formatter the same thing.
And then we have the initClass()
method; this will be used to initialize the class, and all constant fields of the formatters inside the class.
So, let's start making one. Assuming we have a class we want to format in a specific way for our Debug Page.
In this case we have this example class:
public record Foo(String bar, int baz) {}
In the Formatter
class we have a constructor, which have 2 parameters, one class, one resource location.
Making an instance is made like this:
public static final Formatter<Foo> FOO = new Formatter<>(Foo.class, Main.res("foo"));
The Formatter class is abstract too, so we need to implement some things.
It needs to implement the format(...)
method. The method has the instance of the class in the constructor, and a string builder.
@Override
public void format(Foo foo, IFormatterContext context) {
// Do formatting here
}
Now let's do the formatting itself;
context.className("foo")
.other(foo.bar())
.space()
.parameter("baz", foo.baz());
We have some rules in the formatting to have consistent formatting used in all mods. The rules can be found here.
Now we have the parts done, let's assemble it;
public class ExtFormatters {
private static final IFormatterRegistry REGISTRY = IAdvancedDebug.get().getFormatterRegistry();
public static final Formatter<Foo> FOO = REGISTRY.register(new Formatter<>(Foo.class, Main.res("foo")) {
@Override
public void format(Foo foo, IFormatterContext context) {
context.className("foo")
.other(foo.bar())
.space()
.parameter("baz", foo.baz());
}
});
public static void nopInit() {
}
}
The last thing we need to do is initializing the class itself in the extension.
Just call the ExtFormatters.initClass();
in the initFormatters(...)
method.
Like here:
@AdvDebugExt(modId = Main.MOD_ID)
public class AdvancedDebugExtension implements IAdvDebugExt {
@Override
public void initPages(IInitPagesEvent evt) {
// Register pages here
}
@Override
public void initFormatters(IFormatterRegistry registry) {
// Initialize formatters.
ExtFormatters.initClass();
}
}
In the FormatterRegistry object we have a method named register
with 2 parameters, one string, and one formatter class.
© Copyright 2023 - Ultreon Team, All Rights Reserved
Made for the Advanced Debug mod.
For the mod download go to the curseforge or modrinth page.