JDialog
The JDialog class displays a separate window which is "owned" by an application's frame. You can either add your own components to a dialog or use a simple pre-built one through the JOptionPane class. There follows an ActionListener inner class that builds and displays a JDialog consisting of a label, text field and button.
private class ShowDialogButtonListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
JDialog dialog = new JDialog(DemoUI.this, "My Dialog", true);
dialog.setLayout(new FlowLayout());
dialog.add(new JLabel("Name:"));
dialog.add(new JTextField(20));
dialog.add(new JButton("OK"));
dialog.pack();
dialog.setLocationRelativeTo(DemoUI.this);
dialog.setVisible(true);
}
}
The JDialog constructor used above has three arguments passed into it:
- The first argument is the owner, which must either be a frame or another dialog. Because you need this to be the this instance of the outer class (i.e.,
DemoUI) you need to specifyDemoUI.this. If you just specify this, it would refer to the inner class instance instead - The second argument is the text which will appear in the title bar of the dialog
- The third argument of true means that the dialog will be modal. A modal dialog is one which will force the user to close it before any further action can be taken on the owning frame
The dialog is set to use a FlowLayout and then three components are added to it. The size of the dialog is packed, and its display location is set to be relative to the owning frame.
Inside buildUI() create a button that listens for a click by instantiating the above inner class:
JButton showDialogButton = new JButton("Show dialog");
showDialogButton.addActionListener(new ShowDialogButtonListener());
panel.add(showDialogButton);
If you run the application, you should initially just see the button:
Now click the Show dialog button to show the dialog window:
The dialog does not respond to the OK button in this simple example, but you can close the dialog by clicking the window's close button:
You are now returned to the frame.
Comments