Code Patterns

Copy-paste examples for common plugin tasks. Commands, events, ECS, GUI, and more.

← Back to Patterns
ui

Server Stats Display

Display server statistics (CPU, RAM, uptime) in custom UI with auto-refresh

Example Code

java
public class StatsGui extends InteractiveCustomUIPage<StatsGui.Data> {
    private Thread updateThread;

    public StatsGui(PlayerRef playerRef) {
        super(playerRef, CustomPageLifetime.CanDismissOrCloseThroughInteraction, Data.CODEC);
    }

    @Override
    public void build(Ref<EntityStore> ref, UICommandBuilder cmd, UIEventBuilder evt, Store<EntityStore> store) {
        cmd.append("Pages/Stats.ui");

        // Start auto-refresh thread
        this.updateThread = new Thread(() -> {
            while (!Thread.currentThread().isInterrupted()) {
                UICommandBuilder update = new UICommandBuilder();
                buildStats(update);
                this.sendUpdate(update, new UIEventBuilder(), false);
                try { Thread.sleep(5000); } catch (InterruptedException e) { break; }
            }
        });
        this.updateThread.start();
        buildStats(cmd);
    }

    private void buildStats(UICommandBuilder cmd) {
        OperatingSystemMXBean os = ManagementFactory.getOperatingSystemMXBean();
        RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();
        MemoryMXBean memory = ManagementFactory.getMemoryMXBean();

        if (os instanceof com.sun.management.OperatingSystemMXBean sunOS) {
            cmd.set("#CPUUsage.Text", ((int)(sunOS.getSystemCpuLoad()*100)) + "%");
            cmd.set("#CPUBar.Value", sunOS.getSystemCpuLoad());
        }

        var heap = memory.getHeapMemoryUsage();
        cmd.set("#RAMUsage.Text", FormatUtil.bytesToString(heap.getUsed()));
        cmd.set("#RAMBar.Value", heap.getUsed() / (double) heap.getMax());
        cmd.set("#Uptime.Text", FormatUtil.timeUnitToString(runtime.getUptime(), TimeUnit.MILLISECONDS));
    }

    @Override
    protected void close() {
        super.close();
        this.updateThread.interrupt();
    }
}