JOptionPane to get password

后端 未结 6 985
耶瑟儿~
耶瑟儿~ 2020-12-01 13:52

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

6条回答
  •  一向
    一向 (楼主)
    2020-12-01 14:02

    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)

提交回复
热议问题