Having the need to quickly generate dialogs in my game, I looked into the Dialog class in the scene2d.ui package. It allows you to create dialogs with a title, text, and all the buttons you need.
The Dialog object contains a "contentTable" field for its inner text, and a "buttonTable" field where the buttons are placed. Both are Tables. The Dialog class extends Window, which itself is a Table. So you can fine-tune sizes and paddings of the various elements.
Different story for the entire dialog sizing; if you simply use the setSize(w, h) method it won't affect anything. This is because Dialog.show() method calls WidgetGroup.pack(), which overrides any size is explicitly set, and dynamically resizes the group depending on its content. To fix this, you can simply override getPrefWidth() and getPrefHeight() to return the values you need.
I created this class for my needs, which automatically styles the text and buttons you add to the dialog.
public class CustomDialog extends Dialog {
public CustomDialog (String title) {
super(title, Assets.skin);
initialize();
}
private void initialize() {
padTop(60); // set padding on top of the dialog title
getButtonTable().defaults().height(60); // set buttons height
setModal(true);
setMovable(false);
setResizable(false);
}
@Override
public CustomDialog text(String text) {
super.text(new Label(text, Assets.skin, "medium-green"));
return this;
}
/**
* Adds a text button to the button table.
* @param listener the input listener that will be attached to the button.
*/
public CustomDialog button(String buttonText, InputListener listener) {
TextButton button = new TextButton(buttonText, Assets.skin);
button.addListener(listener);
button(button);
return this;
}
@Override
public float getPrefWidth() {
// force dialog width
return 480f;
}
@Override
public float getPrefHeight() {
// force dialog height
return 240f;
}
}
You also need to declare a WindowStyle declaration in your skin.json file.
For more informations about skins, take a look at my
Skin tutorial.
com.badlogic.gdx.scenes.scene2d.ui.Window$WindowStyle: {
default: { background: button-disabled, titleFont: fx35, titleFontColor: red }
}
Example usage in your game screen:
new CustomDialog("Exit game") // this is the dialog title
.text("Leave the game?") // text appearing in the dialog
.button("EXIT", new InputListener() { // button to exit app
public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
Gdx.app.exit();
return false;
}
})
.button("Keep playing") // button that simply closes the dialog
.show(stage); // actually show the dialog
Output: