Reputation: 969
I am creating a simple option pane that asks for multiple user inputs. I have specified the labels and text fields, but at the end of my option pane, there lies a text field that doesn't belong to any variable, so I'm guessing it comes along when specifying the option pane.
Here's my code:
JTextField locationField = new JTextField(10);
JTextField usedByField = new JTextField(5);
JTextField commentField = new JTextField(50);
...
myPanel.add(new JLabel("Location: ");
myPanel.add(locationField);
myPanel.add(new JLabel("Used By: ");
myPanel.add(usedByField);
myPanel.add(new JLabel("Comments: ");
myPanel.add(commentField);
...
JOptionPane.showInputDialog(myPanel);
My dialog ends up looking like this, and as you can see there is a stray text field at the bottom of my pane:
My question is, where in my code would I be secretly specifying this? I don't think I am, so how do I go about in order to get rid of this stray text field that I don't need.
Thank you.
Upvotes: 4
Views: 2585
Reputation: 4385
The solution is simple: don't use JOptionPane.showInputDialog(...)
. Instead use JOptionPane.showMessageDialog(...)
.
The showInputDialog is built to get a single String input from the user, and so it is structured to show an embedded JTextField for this purpose, and returns the String entered into that field, a String that you're not using.
The showMessageDialog on the other hand does not do this, and instead returns an int depending on which of its button has been pressed.
Please have a look at the JOptionPane API for more on this.
Edit: I was wrong. Use a JOptionPane.showConfirmDialog(...)
if you want the dialog to supply dialog-handling buttons, such as "OK", "Cancel" or "Yes" and "No" and to allow the user to press these buttons and then get input from the button.
For example:
final JTextField userNameField = new JTextField(10);
final JPasswordField passwordField = new JPasswordField(10);
JPanel pane = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0,
GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL,
new Insets(2, 2, 2, 2), 0, 0);
pane.add(new JLabel("User Name:"), gbc);
gbc.gridy = 1;
pane.add(new JLabel("Password:"), gbc);
gbc.gridx = 1;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.EAST;
pane.add(userNameField, gbc);
gbc.gridy = 1;
pane.add(passwordField, gbc);
int reply = JOptionPane.showConfirmDialog(null, pane, "Please Log-In",
JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
if (reply == JOptionPane.OK_OPTION) {
// get user input
String userName = userNameField.getText();
// ****** WARNING ******
// ** The line below is unsafe code and makes a password potentially discoverable
String password = new String(passwordField.getPassword());
System.out.println("user name: " + userName);
System.out.println("passowrd: " + password);
}
which displays:
Upvotes: 6