commit ef25e1307fb90fd9c8e842adf03411153fa86ce7
parent d817fef363749b29f3d119f3759a05fd868b51ed
Author: Wim Dupont <wim@wimdupont.com>
Date:   Tue, 28 Feb 2023 22:57:42 +0100
focus on input window
Diffstat:
1 file changed, 22 insertions(+), 6 deletions(-)
diff --git a/src/main/java/com/wimdupont/service/GpgUtil.java b/src/main/java/com/wimdupont/service/GpgUtil.java
@@ -18,7 +18,9 @@ import org.bouncycastle.openpgp.operator.bc.BcPBESecretKeyDecryptorBuilder;
 import org.bouncycastle.openpgp.operator.bc.BcPGPDigestCalculatorProvider;
 import org.bouncycastle.openpgp.operator.bc.BcPublicKeyDataDecryptorFactory;
 
+import javax.swing.JLabel;
 import javax.swing.JOptionPane;
+import javax.swing.JPanel;
 import javax.swing.JPasswordField;
 import java.io.ByteArrayOutputStream;
 import java.io.Console;
@@ -68,20 +70,34 @@ public class GpgUtil {
                     .orElseThrow(() -> new RuntimeException("File not found"));
         }
 
-        System.out.println("Type in GPG password.");
+        return decryptFile(new FileInputStream(file.getAbsolutePath()), getPassword());
+    }
+
+    public static char[] getPassword() {
+        String prompt = "Enter password";
         Console cons = System.console();
         char[] pwd;
         if (cons != null) {
+            System.out.println(prompt);
             pwd = cons.readPassword();
         } else {
-            final JPasswordField passwordField = new JPasswordField();
-            pwd = JOptionPane.showConfirmDialog(null, passwordField, "Enter password",
-                    JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.OK_OPTION
-                    ? (passwordField.getPassword()) : new char[0];
+            JPanel panel = new JPanel();
+            final JPasswordField passwordField = new JPasswordField(10);
+            panel.add(new JLabel("Password"));
+            panel.add(passwordField);
+            JOptionPane pane = new JOptionPane(panel, JOptionPane.QUESTION_MESSAGE, JOptionPane.OK_CANCEL_OPTION) {
+                @Override
+                public void selectInitialValue() {
+                    passwordField.requestFocusInWindow();
+                }
+            };
+            pane.createDialog(null, prompt).setVisible(true);
+            pwd = passwordField.getPassword().length == 0 ? new char[0] : passwordField.getPassword();
         }
-        return decryptFile(new FileInputStream(file.getAbsolutePath()), pwd);
+        return pwd;
     }
 
+
     private Properties loadProperties() {
         final Properties properties = new Properties();
         InputStream inputStream = getClass().getResourceAsStream("/application.properties");