Can anyone show/point me to example of simple JDialog called from JFrame?
Printable View
Can anyone show/point me to example of simple JDialog called from JFrame?
This is an example of the creation and display of a simple custom dialog.
Somewhere in our class we declare the following global objects:
private JFrame mainFrame = new JFrame();
private JDialog nameDialog = new JDialog(mainFrame, "User Name Entry", true);
This method created the components that the dialog will display and use:
public Component createComponents()
{
JPanel mainPane = new JPanel();
JPanel textPane = new JPanel();
JPanel buttonPane = new JPanel();
JLabel nameLabel = new JLabel("Please enter your username:");
nameLabel.setForeground(Color.black);
uname = new JTextField(20);
okButton = new JButton("OK");
okButton.setMnemonic('o');
okButton.setSelected(true);
okButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
userName = uname.getText();
if (userName.equals(null) || userName.equals("") || userName.equals(" "))
{
JOptionPane.showMessageDialog(nameDialog,
"Please enter a valid user name.",
"Invalid User Name",
JOptionPane.WARNING_MESSAGE);
} //end if
else
{
mainFrame.dispose();
nameDialog.dispose();
} //end else
} //end actionPerformed
}); //end addActionListener
textPane.setLayout(new BoxLayout(textPane,BoxLayout.X_AXIS));
textPane.add(nameLabel);
textPane.add(uname);
buttonPane.setLayout(new BoxLayout(buttonPane,BoxLayout.X_AXIS));
buttonPane.add(okButton);
mainPane.setLayout(new BoxLayout(mainPane,BoxLayout.Y_AXIS));
mainPane.add(textPane);
mainPane.add(buttonPane);
return mainPane;
} //end createComponents
To display the JDialog, do this:
nameDialog.setSize(new Dimension(230,73));
nameDialog.getContentPane().add(createComponents());
nameDialog.getRootPane().setDefaultButton(okButton);
nameDialog.show();
Please let me know if you have any more questions.
"There's nothing more dangerous than a resourceful idiot." ---Dilbert
Thank you, fixed my problem...didn't have the main frame defined on the dialog properly.
One question though, my main frame is still active, how do I block that out, ie. not allow focus on it until a response from my dialog?
I think you just need to do a setModal(true) on the dialog. That will make the dialog modal, and prevent use of your main window until the dialog has finished.
"There's nothing more dangerous than a resourceful idiot." ---Dilbert
Much thanks again...working like a charm!