Get Dialog Data
Learn how to ensure the entered text is valid or invalid before closing the dialog.
Now in this lesson, we will ensure that the dialog takes valid input before closing. A program user can type anything into a text field. You will first create an OK button which when clicked, checks whether the input entered, is valid or not. If the entered text is not valid, the program will ask the user to correct the text before closing the dialog.
Let’s get started!
Adding a button to close the dialog
Next, retrieve information from the dialog. First, add an OK button which will close the dialog when clicked.
- In the button panel section of the constructor, create a
JPanel
object calledbuttonPanel
. - Add
buttonPanel
to the bottom of the dialog. (Hint: useJDialog
'sadd()
method and BorderLayout’sPAGE_END
variable.) - Create a
JButton
object calledokButton
, with text"OK"
. - Add an actionListener to
okButton
to callclose()
when the button is clicked. (Hint: useJButton
'saddActionListener()
method, with a newActionListener
object as the parameter value. In theActionListener
, add a public method calledactionPerformed()
.actionPerformed()
should have one parameter, anActionEvent
, and return nothing. InactionPerformed()
, callclose()
.) - Add
okButton
tobuttonPanel
.
...
public OptionsDialog(int rows, int cols, int type) {
...
// button panel
___________ buttonPanel = ____________;
add(_____________________);
___________ okButton = ________________;
okButton.addActionListener(________________ {
________________ actionPerformed(__________) {
_____________();
}
});
buttonPanel.____________;
}
Note: The code will have a syntax error because close()
doesn’t exist yet.
Get hands-on with 1200+ tech skills courses.