解決方法很簡單:不要使用JOptionPane.showInputDialog(...)
。請使用JOptionPane.showMessageDialog(...)
。
showInputDialog構建爲從用戶獲取單個字符串輸入,因此它被構造爲顯示一個嵌入的JTextField用於此目的,並返回輸入到該字段中的字符串,這是您不使用的字符串。
另一方面,showMessageDialog不執行此操作,而是根據按鈕的哪個按鈕被按下而返回int。
請查看JOptionPane API瞭解更多。
編輯:我錯了。如果您希望對話框提供對話框處理按鈕,如「確定」,「取消」或「是」和「否」,並允許用戶按下這些按鈕,然後從按鈕獲得輸入,請使用JOptionPane.showConfirmDialog(...)
。
例如:
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);
}
其中顯示:

真棒,太感謝你了。我會更多地關注它,但現在它正在按照我的期望工作。 – juiceb0xk
@ juiceb0xk:非常歡迎你,祝你好運! –
@ juiceb0xk:我錯了。請參閱編輯。 –