JOptionPane can be used to get string inputs from user, but in my case, I want to display a password field in showInputDialog.
The way I ne
A Kotlin solution based on Adamski's answer.
This time without buttons that takes focus, just enter password and press Enter, or Escape to discard input:
class PasswordPanel : JPanel(FlowLayout()) {
private val passwordField = JPasswordField(20)
private var entered = false
val enteredPassword
get() = if (entered) String(passwordField.password) else ""
init {
add(JLabel("Password: "))
add(passwordField)
passwordField.setActionCommand("OK")
passwordField.addActionListener {
if (it.actionCommand == "OK") {
entered = true
// https://stackoverflow.com/a/51356151/1020871
SwingUtilities.getWindowAncestor(it.source as JComponent)
.dispose()
}
}
}
private fun request(passwordIdentifier: String) = apply {
JOptionPane.showOptionDialog(null, this@PasswordPanel,
"Enter $passwordIdentifier",
JOptionPane.DEFAULT_OPTION,
JOptionPane.INFORMATION_MESSAGE,
null, emptyArray(), null)
}
companion object {
fun requestPassword(passwordIdentifier: String) = PasswordPanel()
.request(passwordIdentifier)
.enteredPassword
}
}
Usage: PasswordPanel.requestPassword(passwordIdentifier)