Set a Default Button

Learn how to set a button as default in the dialog.

A default button

We can set one button in a dialog or window to be the default button. Pressing the Enter key will activate a default button no matter which component is in focus. Using a default button is especially convenient with input text fields in the dialog or window. The program user can then just press the Enter key when done typing the text.

So in this lesson, we will learn to set a button in the dialog to be the default button.

Setting a default button

At the end of OptionsDialog's constructor, get the root pane and set the default button to okButton.

...
public OptionsDialog(int rows, int cols, int type) {
...
buttonPanel.add(cancelButton);
getRootPane().setDefaultButton(____________);
}
...

Get hands-on with 1200+ tech skills courses.