如何让我的对话框显示我的程序输出?

时间:2016-12-15 08:22:05

标签: java swing dialog joptionpane

我们最近在课堂上浏览了对话框并分配了作业。

分配是设计和实现一个应用程序,该应用程序使用对话框获取两个整数值(每个值一个对话框)并显示值的总和和乘积。使用另一个对话框询问用户是否要处理另一对值。

到目前为止,我尝试了这个项目,但是我遇到了一行代码问题,我在那里展示了我的答案。我正在使用NetBeans IDE,并使用显示方法JOptionPane.showConfirmDialog来显示我的答案。它一直给我一个错误,上面写着“showMessageDialog找不到合适的方法。”我试图使用System.out.println,但它也给了我错误,所以我回到了方法。你能解释一下如何修复它以及我的代码错误的原因吗?

这是我到目前为止的代码:

package DialogBoxes;

import javax.swing.JOptionPane;
/**
 *
 * @author Tony
 */

public class SumProduct {
/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    // TODO code application logic here
    String askNum1, askNum2, answerSum, answerPro;
    int num1, num2, repeat;

    do 
    { 
        askNum1 = JOptionPane.showInputDialog ("Enter your first integer:");
        num1 = Integer.parseInt(askNum1);

        askNum2 = JOptionPane.showInputDialog("Enter your second integer:");
        num2 = Integer.parseInt(askNum2);

        answerSum = "The sum is: " + ((num1 + num2));
        answerPro = "The product is: " + ((num1 * num2));

        JOptionPane.showMessageDialog(null, answerSum, answerPro);

        repeat = JOptionPane.showConfirmDialog(null, "Would you like to test another set of numbers?");           
    }
    while (repeat == JOptionPane.YES_OPTION);
}
}

3 个答案:

答案 0 :(得分:2)

您可以使用JOptionPane.showMessageDialog(parentComponent, message);方法

您需要创建一个带有产品和总和的String,如下所示并将其传递给showMessageDialog

JOptionPane.showMessageDialog(null, answerSum + "  " + answerPro);

答案 1 :(得分:1)

查看JOptionPane API:https://docs.oracle.com/javase/7/docs/api/javax/swing/JOptionPane.html#showMessageDialog(java.awt.Component,%20java.lang.Object)

看起来不像只有3个参数的showMessageDialog方法。您需要使用API​​提供的方法之一。

答案 2 :(得分:1)

请试一试。快乐的编码。

package com.pearson.nextgen.aggregatedsessionservice.web.rest;

import javax.swing.JFrame;
import javax.swing.JOptionPane;

    public class stacktest {

        public static void main(String[] args) {
            // TODO code application logic here
            String askNum1, askNum2, answerSum, answerPro;
            int num1, num2, repeat;

            do 
            { 
                askNum1 = JOptionPane.showInputDialog ("Enter your first integer:");
                num1 = Integer.parseInt(askNum1);

                askNum2 = JOptionPane.showInputDialog("Enter your second integer:");
                num2 = Integer.parseInt(askNum2);

                answerSum = "The sum is: " + ((num1 + num2));
                answerPro = " The product is: " + ((num1 * num2));

                JFrame frame = new JFrame("TestFrame");
                JOptionPane.showMessageDialog(null, answerSum + answerPro);

                repeat = JOptionPane.showConfirmDialog(null, "Would you like to test another set of numbers?");           
            }
            while (repeat == JOptionPane.YES_OPTION);

        }

    }