繁体   English   中英

Java JOptionPane单个输入中的多个输入和算术运算

[英]Java JOptionPane Multiple Inputs and Arithmetic Operations In a Single Output

我已经开始学习有关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);

好吧...如果您希望在一个对话框中有多个输入,则可以使用JOptionPane.showConfirmDialog()方法并为其提供自定义JPanel(此处提供一些示例 )。 换句话说,您将创建一个自定义对话框。

就您而言,这是一种实现方法:

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

您可以修改此概念以适合您的需求。

暂无
暂无

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

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