Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Java Swing : A simple applet to calculate phone bill

Posted on 2006-11-19
6
Medium Priority
?
2,910 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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
The top UI technologies you need to be aware of

An important part of the job as a front-end developer is to stay up to date and in contact with new tools, trends and workflows. That’s why you cannot miss this upcoming webinar to explore the latest trends in UI technologies!

 
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 2000 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

Build and deliver software with DevOps

A digital transformation requires faster time to market, shorter software development lifecycles, and the ability to adapt rapidly to changing customer demands. DevOps provides the solution.

Question has a verified solution.

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

INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.
How to fix incompatible JVM issue while installing Eclipse While installing Eclipse in windows, got one error like above and unable to proceed with the installation. This video describes how to successfully install Eclipse. How to solve incompa…
Suggested Courses

722 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