Search code examples
javaintellij-idealibgdx

How to create a main menu using libgdx and java


Ive been playing around with libgdx for the past couple of days and I wanted to see if someone could give a simple example of how a main menu screen is created with a start button and exit button.


Solution

  • LibGDX suggests to use its "scene2d" component if you need to build a UI.

    The simplest example can be found on LibGDX's Wiki right in the article about scene2d: https://libgdx.com/wiki/graphics/2d/scene2d/scene2d

    Actually, the first code example from the wiki will do - it is a bit modified by me and shoud be added to your implementation of Screen or Game:

    private Stage stage;
    
    @Override
    public void create () {
        stage = new Stage(new ScreenViewport());
        Gdx.input.setInputProcessor(stage);
    
        // Insert your UI elements here, for example:
        Skin skin = new Skin(Gdx.files.internal("skin.json")); // https://libgdx.com/wiki/graphics/2d/scene2d/skin
        Table menuContainer = new Table();
        TextButton playButton = new TextButton("Play", skin);
        playButton.addListener(new ClickListener() {
            @Override
            public void clicked (InputEvent event, float x, float y) {
                // Called when player clicks on Play button
            }
        });
        menuContainer.add(playButton);
    
        TextButton exitButton = new TextButton("Exit", skin);
        exitButton.addListener(new ClickListener() {
            @Override
            public void clicked (InputEvent event, float x, float y) {
                // Called when player clicks on Exit button
            }
        });
        menuContainer.add(exitButton);
    }
    
    @Override
    public void resize (int width, int height) {
        // See below for what true means.
        stage.getViewport().update(width, height, true);
    }
    
    @Override
    public void render () {
        float delta = Gdx.graphics.getDeltaTime();
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        stage.act(delta);
        stage.draw();
    }
    
    @Override
    public void dispose () {
        stage.dispose();
    }