dan
dan

Reputation: 127

Make JOptionPane Print More Than One Set Of Data

Can someone explain to me how I can print all three rows of customer data in one dialog box like in the screenshot below? Right now it only prints one row at a time.

joptionprint

String custNum = JOptionPane.showInputDialog("Enter cust numb:");
      while (!custNum.equalsIgnoreCase("quit")) {
         String custName = JOptionPane.showInputDialog("Enter cust name:");
         do {
            try {
               kilowattUsed = Double.parseDouble(JOptionPane.showInputDialog("Enter kilowatt(s) used:"));
            }
            catch (NumberFormatException e) {
               kilowattUsed = minKilowatt - 1;
            }
            if (kilowattUsed < minKilowatt || kilowattUsed >= maxKilowatt) {
               JOptionPane.showMessageDialog(null,"Please enter a valid number");
            }
         } while (kilowattUsed <= minKilowatt || kilowattUsed >= maxKilowatt);


         if (kilowattUsed < lowRateKilowattMin) {
            amtOwed = kilowattUsed * highRate;
         }
         else {
            amtOwed = kilowattUsed * lowRate;
         }

         totalOwed += amtOwed;
         numCustomers++;
         JOptionPane.showMessageDialog(null,custNum + " | " + custName + " | " 
            + String.format("%.1f",kilowattUsed) + " | " + "$" + String.format("%.2f",amtOwed));

         custNum = JOptionPane.showInputDialog("Enter cust number:");
      }

Upvotes: 1

Views: 141

Answers (2)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285430

A key understanding to note is that the 2nd parameter of your JOptionPane's show method can be any Swing component, including a JTable, which is the best component for showing tabular data. So I suggest that you,

  • Use your data to fill a DefaultTableModel
  • Create a JTable using that model
  • Place the JTable in a JScrollPane
  • Pass that JScrollPane as the 2nd parameter of your JOptionPane.showMessageDialog(...)

Upvotes: 1

Roan
Roan

Reputation: 1206

The chacter you use in java for a new line is the new line character \n so if you add that in your final string between your lines then they will come on seprerate lines:

Here is a simple example to demonstrate it:

JOptionPane.showMessageDialog(null, "line1 \nline2 \nline3");

The output of this will be:

enter image description here

I hope this helps :)

Upvotes: 1

Related Questions