Solved

Java Swing : A simple applet to calculate phone bill

Posted on 2006-11-19
6
2,654 Views
Last Modified: 2013-11-23
Dear experts:

Hi again!

I am creating a simple Java applet to calculate a phone bill based on plans (unlimited vs. 300 anytime minutes with  45 cents for additional minute).



I would like to ctreate a display as the follows:

     Name :                     Textfield              // Users will type in their names

Anytime Usage:              Textfield             // Users will type in their phone usage (total minutes used)

      Total :                     Textfield             // Total Textfield

                                 Calculate Button      // When "Calculate" button is pressed,
                                                             // total will be calculated and displayed on the textfield of total.


I am an absolute novice in Swing, and my code (below) is miserably poor.  If you experts may kindly fix the code, it will
be of a tremendous help to me.

Thanks a lot!


___________________  Here is my code _____________________________________


import javax.swing.JOptionPane;
import java.text.DecimalFormat;
import java.util.regex.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

public class PhoneBill extends JApplet
{
   
  private JList  planList;
 
  private JPanel Pname;
  private JPanel Pusage;
  private JPanel Ptotal;
  private JPanel Pbutton
 
  private JTextField Fname;
  private JTextField Fusage;
  private JTextField Ftotal;
  private Container c;
 
  private String plans [] = {"Unlimited Plan", "Limited Plan"};
 
  public void init ( )
  {
    // Methods to build the panels
    buildPlan ();
    buildName ();
    buildUsage ();
    buildTotal ();
    buildButton ();
   
    // Create a layout manager
    setLayout ( new GridLayout (5, 1 ) );
   
    // Add the panels to the content pane
    add ( Pname);
    add ( planList );
    add ( Pusage);
    add ( Ptotal );
    add ( Pbutton );
  }
   
  private void buildPlan ()
  {
   
    Pname = new JPanel ();
   
    planList = new JList ( plans );
    planList.setVisibleRowCount (12);
   
    // Do not allow multiple selections
    planList.setSelectionMode ( ListSelectionModel.SINGLE_SELECTION );
   
    // add a JScrollPane containing the planList to the content pane
    c.add ( new JScrollPane (planList ) );
   
 }
 
  private void buildName ()
  {
    Pname = new JPanel ( );
    JLabel message1 = new JLabel ("Your Name : " );
    Fname =  new JTextField ( 20 );
    Fname.setEditable ( false );
   
    Pname.setLayout ( new FlowLayout ( FlowLayout.RIGHT ) );
    Pname.add (message1);
    Pname.add ( Fname );
  }
 
  private void buildUsage ()
  {
    Pusage = new JPanel ( );
    JLabel message2 = new JLabel ("Your Anytime Usage : " );
    Fusage =  new JTextField ( 20 );
    Fusage.setEditable ( false );
   
    Pusage.setLayout ( new FlowLayout ( FlowLayout.RIGHT ) );
    Pusage.add (message2);
    Pusage.add ( Fusage );
  }
 
  private void buildTotal ()
  {
    Ptotal = new JPanel ( );
    JLabel message3 = new JLabel ("Your Total Charge: " );
    Ftotal =  new JTextField ( 20 );
    Ftotal.setEditable ( false );
   
    Ptotal.setLayout ( new FlowLayout ( FlowLayout.RIGHT ) );
    Ptotal.add (message3);
    Ptotal.add ( Ftotal );
  }
 
 private void buildButton ()
  {
    Pbutton = new JPanel ( );
    JButton calcButton = new JButton ( "Calculate");
    calcButton.addActionListener ( new ButtonListener ( ) );
    Pbutton.add ( calcButton );
  }
 
 // Private inner class that andles the action event that is generated
 // when the user clicks "Calculate" button.
 
 
 private class ButtonListner implements ActionListener
 {
   public void actionPerformed ( ActionEvent e )
   {
     String name = " ";
     int mins_used = 0;
     String plan = " ";
     float total = 0.0f;
     
     name = Pname.getText ();
     mins_used = Integer.parseInt (Pusage.getText () );
     plan = planList.getSelectedIndex ();
     if (plan.equals ("LIMITED_PLAN") )
           
         if (mins_used <= 300 )
          {
             total = 39.99f;
             Ptotal.setText (total);
          }
         else
           {
            total = 39.99f + ((mins_used - 300) * 0.45f);
            Ptotal.setText (total);
         }
      else
           {
              total = 69.99f;
              Ptotal.setText (total);
           }
         
    }
 }
     
     
 








0
Comment
Question by:duta
6 Comments
 
LVL 16

Expert Comment

by:suprapto45
ID: 17976584
Hi,

What is wrong with your codes now?

I can see one basic error such as

     if (plan.equals ("LIMITED_PLAN") )
           
         if (mins_used <= 300 )
          {
             total = 39.99f;
             Ptotal.setText (total);
          }
         else
           {
            total = 39.99f + ((mins_used - 300) * 0.45f);
            Ptotal.setText (total);
         }
      else
           {
              total = 69.99f;
              Ptotal.setText (total);
           }

You should have the open and closing braces after the first IF as

     if (plan.equals ("LIMITED_PLAN") )
     {  // LOOK HERE      
         if (mins_used <= 300 )
          {
             total = 39.99f;
             Ptotal.setText (total);
          }
         else
           {
            total = 39.99f + ((mins_used - 300) * 0.45f);
            Ptotal.setText (total);
         }
     }  // LOOK HERE      
      else
           {
              total = 69.99f;
              Ptotal.setText (total);
           }
0
 
LVL 16

Expert Comment

by:suprapto45
ID: 17976588
>>"What is wrong with your codes now?"
I do not have any jdk installed in my machine at the moment so can't really test your codes. So just let me know what is wrong with your current codes.
0
 
LVL 5

Expert Comment

by:deeppra
ID: 17977296
tell me whats the problem in ur code so that we can fix it
0
Live: Real-Time Solutions, Start Here

Receive instant 1:1 support from technology experts, using our real-time conversation and whiteboard interface. Your first 5 minutes are always free.

 
LVL 10

Expert Comment

by:ADSLMark
ID: 17977352
You forgot a ; after the private JPanel Pbutton (line 18)
You forgot a closing } from the whole class. (line 141)
You cannot setText on a JPanel, you should change the Ptotal into Ftotal and add empty quotes to convert to string (line 127, 132, 137):

Ptotal.setText (total);
=>
Ftotal.setText (""+total);

Same for getText, use it on the JTextfields, not the JPanels (line 119, 120)

getSelectedIndex delivers a integer, not a string. You have to get the string from the plans array, ie.
int plan = 0; //remove the String plan = " ";
if (plan>=0 && plan<plans.length && plans[plan].equals ("Limited Plan") )

You could also do:
if(plan==1)


small typo in the inner class declaration:
private class ButtonListner implements ActionListener
=>
private class ButtonListener implements ActionListener

I did not test further (have to go now)

Mark
0
 
LVL 10

Accepted Solution

by:
ADSLMark earned 500 total points
ID: 17977565
Oke i did some further checking..

in the method buildPlan() you call a method on the object c, but c is not instantiated. I looked at the whole buildPlan() method and figured you do not want it in the Pname panel but just as single control, so i remove the Pname = new JPanel() and c.add statements.

then the functionality of your program had to be changed. For instance, textfields which were non-editable and in your description you ask people to enter data, so that's one.

Also the parsing of some string can throw a NumberFormatException which i added.

And added a default selection to the JList (being the first item).

Resulting code:

import javax.swing.JOptionPane;
import java.text.DecimalFormat;
import java.util.regex.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

public class PhoneBill extends JApplet
{
   
  private JList  planList;
 
  private JPanel Pname;
  private JPanel Pusage;
  private JPanel Ptotal;
  private JPanel Pbutton;
 
  private JTextField Fname;
  private JTextField Fusage;
  private JTextField Ftotal;
  private Container c;
 
  private String plans [] = {"Unlimited Plan", "Limited Plan"};
 
  public void init ( )
  {
    // Methods to build the panels
    buildPlan ();
    buildName ();
    buildUsage ();
    buildTotal ();
    buildButton ();
   
    // Create a layout manager
    setLayout ( new GridLayout (5, 1 ) );
   
    // Add the panels to the content pane
    add ( Pname);
    add ( planList );
    add ( Pusage);
    add ( Ptotal );
    add ( Pbutton );
  }
   
  private void buildPlan ()
  {
    planList = new JList ( plans );
    planList.setVisibleRowCount (12);
   
    // Do not allow multiple selections
    planList.setSelectionMode ( ListSelectionModel.SINGLE_SELECTION );
    planList.setSelectedIndex(0);
   
 }
 
  private void buildName ()
  {
    Pname = new JPanel ( );
    JLabel message1 = new JLabel ("Your Name : " );
    Fname =  new JTextField ( 20 );
   
    Pname.setLayout ( new FlowLayout ( FlowLayout.RIGHT ) );
    Pname.add (message1);
    Pname.add ( Fname );
  }
 
  private void buildUsage ()
  {
    Pusage = new JPanel ( );
    JLabel message2 = new JLabel ("Your Anytime Usage : " );
    Fusage =  new JTextField ( 20 );
   
    Pusage.setLayout ( new FlowLayout ( FlowLayout.RIGHT ) );
    Pusage.add (message2);
    Pusage.add ( Fusage );
  }
 
  private void buildTotal ()
  {
    Ptotal = new JPanel ( );
    JLabel message3 = new JLabel ("Your Total Charge: " );
    Ftotal =  new JTextField ( 20 );
    Ftotal.setEditable ( false );
   
    Ptotal.setLayout ( new FlowLayout ( FlowLayout.RIGHT ) );
    Ptotal.add (message3);
    Ptotal.add ( Ftotal );
  }
 
 private void buildButton ()
  {
    Pbutton = new JPanel ( );
    JButton calcButton = new JButton ( "Calculate");
    calcButton.addActionListener ( new ButtonListener ( ) );
    Pbutton.add ( calcButton );
  }
 
 // Private inner class that andles the action event that is generated
 // when the user clicks "Calculate" button.
 
 
 private class ButtonListener implements ActionListener
 {
   public void actionPerformed ( ActionEvent e )
   {
     String name = " ";
     int mins_used = 0;
     int plan = 0;
     float total = 0.0f;
     
     name = Fname.getText ();
     try
     {
           mins_used = Integer.parseInt (Fusage.getText () );
             plan = planList.getSelectedIndex ();
             if (plan==1 )
             {      
                 if (mins_used <= 300 )
                  {
                     total = 39.99f;
                     Ftotal.setText (""+total);
                  }
                 else
                   {
                    total = 39.99f + ((mins_used - 300) * 0.45f);
                    Ftotal.setText (""+total);
                 }
                                }
              else
             {
                      total = 69.99f;
                      Ftotal.setText (""+total);
              }
     }
     catch(NumberFormatException nfe)
     {
           Ftotal.setText ("Please enter an integer by usage.");
     }
         
    }
 }
}

I hope it helps and implements the functionality you want.
Mark
0
 

Author Comment

by:duta
ID: 17979576
Marm, you are just awesome again.
Your code is working great.

I am responding upon testing your corrections this morning.

I just began to learn Swing, and I hope to learn more by expanding the code.
I will certainly come back with some more questions.
Hope you may kindly help me again.

Thanks a lot!

p.s.: My thanks go to others who kindly tried to help me.

0

Featured Post

Courses: Start Training Online With Pros, Today

Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
reverse digits of a number using for loop 5 40
What's wrong with this code? 4 22
pagenation logic how it is working in my code 1 27
String array comparison 4 32
Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:

786 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question