Java JOptionPane.showInputDialog 中的多个输入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6555040/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 07:42:24  来源:igfitidea点击:

Multiple input in JOptionPane.showInputDialog

javaswingjoptionpane

提问by siaooo

Is there a way to create multiple input in JOptionPane.showInputDialoginstead of just one input?

有没有办法创建多个输入JOptionPane.showInputDialog而不是一个输入?

采纳答案by Hovercraft Full Of Eels

Yes. You know that you can put any Objectinto the Objectparameter of most JOptionPane.showXXX methods, and often that Objecthappens to be a JPanel.

是的。您知道可以将 anyObject放入Objectmost的参数中JOptionPane.showXXX methods,而且通常Object恰好是JPanel.

In your situation, perhaps you could use a JPanelthat has several JTextFieldsin it:

在您的情况下,也许您可​​以使用JPanel其中包含多个的a JTextFields

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());
      }
   }
}

回答by smidhonza

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");
}