簡體   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