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.

  1. In the button panel section of the constructor, create a JPanel object called buttonPanel.
  2. Add buttonPanel to the bottom of the dialog. (Hint: use JDialog's add() method and BorderLayout’s PAGE_END variable.)
  3. Create a JButton object called okButton, with text "OK".
  4. Add an actionListener to okButton to call close() when the button is clicked. (Hint: use JButton's addActionListener() method, with a new ActionListener object as the parameter value. In the ActionListener, add a public method called actionPerformed(). actionPerformed() should have one parameter, an ActionEvent, and return nothing. In actionPerformed(), call close().)
  5. Add okButton to buttonPanel.
...
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.