【问题标题】:Java JOptionPane Multiple Inputs and Arithmetic Operations In a Single OutputJava JOptionPane 单个输出中的多个输入和算术运算
【发布时间】:2018-04-14 13:45:03
【问题描述】:

我已经开始学习关于 Java 的课程,并且刚刚了解了 JOptionPane,我们对用户在输入对话框窗口中给出的输入进行了一些算术运算,但每个输入都有不同的对话框,然后进行运算并显示在消息框中向用户输出。

我想知道的是,如何在一个框中获取用户的所有输入并在消息框中将输出显示给用户?

这是我们已经处理过的示例的代码。

    double ap = 0.3;
    double op = 0.2;
    double fp = 0.5;


    String a = JOptionPane.showInputDialog(null,"Input A:");
    String b = JOptionPane.showInputDialog(null,"Input B:");
    String c = JOptionPane.showInputDialog(null,"Input C:");
    String d = JOptionPane.showInputDialog(null,"Input D:");

    double aValue =  (Double.parseDouble(a)*ap);
    double bcValue = (((Double.parseDouble(b)/2(Double.parseDouble(c)/2))*op);
    double fValue = (Double.parseDouble(d)*fp);

    double res = aValue+bcValue+fValue;


    JOptionPane.showMessageDialog(null,"Result : " +res);

【问题讨论】:

    标签: java math input joptionpane operations


    【解决方案1】:

    嗯...如果您想在一个对话框中有多个输入,那么您可以使用 JOptionPane.showConfirmDialog() 方法并为其提供自定义 JPanel(此处为 examples)。换句话说,您创建了一个自定义对话框。

    在你的情况下,这是你可以做到的一种方法:

    String dialogMessage = "Please suppliy digits to the following<br>input boxes:";
    int btns = JOptionPane.OK_CANCEL_OPTION;
    BorderLayout layout = new BorderLayout();
    JPanel panel = new JPanel(layout);
    JLabel label = new JLabel("<html>" + dialogMessage + "<br><br><br></html>");
    panel.add(label, BorderLayout.NORTH);
    
    JPanel p = new JPanel(new BorderLayout(5, 5));
    JPanel labels = new JPanel(new GridLayout(0, 1, 2, 2));
    labels.add(new JLabel("Input A", SwingConstants.RIGHT));
    labels.add(new JLabel("Input B", SwingConstants.RIGHT));
    labels.add(new JLabel("Input C", SwingConstants.RIGHT));
    labels.add(new JLabel("Input D", SwingConstants.RIGHT));
    p.add(labels, BorderLayout.WEST);
    
    JPanel controls = new JPanel(new GridLayout(0, 1, 2, 2));
    JTextField inputA = new JTextField();
    controls.add(inputA);
    JTextField inputB = new JTextField();
    controls.add(inputB);
    JTextField inputC = new JTextField();
    controls.add(inputC);
    JTextField inputD = new JTextField();
    controls.add(inputD);
    p.add(controls, BorderLayout.CENTER);
    panel.add(p);
    
    // Get Input from User...
    int res = JOptionPane.showConfirmDialog(null, panel, "My Dialog Title", btns);
    if (res == JOptionPane.OK_OPTION) {
        System.out.println("Input A is: " + inputA.getText());
        System.out.println("Input B is: " + inputB.getText());
        System.out.println("Input C is: " + inputC.getText());
        System.out.println("Input D is: " + inputD.getText());
    }
    

    您可以修改此概念以满足您的需要。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-02
      • 2019-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多