简体   繁体   English

JOptionPane.showInputDialog 中的多个输入

[英]Multiple input in JOptionPane.showInputDialog

Is there a way to create multiple input in JOptionPane.showInputDialog instead of just one input?有没有办法在JOptionPane.showInputDialog中创建多个输入,而不仅仅是一个输入?

Yes.是的。 You know that you can put any Object into the Object parameter of most JOptionPane.showXXX methods , and often that Object happens to be a JPanel .您知道您可以将任何Object放入大多数JOptionPane.showXXX methodsObject参数中,并且通常Object恰好是JPanel

In your situation, perhaps you could use a JPanel that has several JTextFields in it:在您的情况下,也许您可以使用其中包含多个JTextFieldsJPanel

import javax.swing.*;

public class JOptionPaneMultiInput {
   public static void main(String[] args) {
      JTextField xField = new JTextField(5);
      JTextField yField = new JTextField(5);

      JPanel myPanel = new JPanel();
      myPanel.add(new JLabel("x:"));
      myPanel.add(xField);
      myPanel.add(Box.createHorizontalStrut(15)); // a spacer
      myPanel.add(new JLabel("y:"));
      myPanel.add(yField);

      int result = JOptionPane.showConfirmDialog(null, myPanel, 
               "Please Enter X and Y Values", JOptionPane.OK_CANCEL_OPTION);
      if (result == JOptionPane.OK_OPTION) {
         System.out.println("x value: " + xField.getText());
         System.out.println("y value: " + yField.getText());
      }
   }
}

this is my solution这是我的解决方案

JTextField username = new JTextField();
JTextField password = new JPasswordField();
Object[] message = {
    "Username:", username,
    "Password:", password
};

int option = JOptionPane.showConfirmDialog(null, message, "Login", JOptionPane.OK_CANCEL_OPTION);
if (option == JOptionPane.OK_OPTION) {
    if (username.getText().equals("h") && password.getText().equals("h")) {
        System.out.println("Login successful");
    } else {
        System.out.println("login failed");
    }
} else {
    System.out.println("Login canceled");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM