Solved

Java Swing: ComboBox Problem

Posted on 2006-11-20
11
599 Views
Last Modified: 2013-11-23
Hi experts again!

I have a simple code to calculate phone bill based on phone plan and anytime usage.

The problem is with the combobox which enables the clients to choose between: (1) "Unlimited Plan: and (2) "Limited Plan".

The current code (below) is a modification of a code which worked just great when the phone plan option was JList ( genius Mark helped me a lot with the current code).

I just want to learn how to do the plan selection with ComboBox. The code which involves ComboBox is less than half-cooked because frankly I am very dark about how to use ComboBox (I checked Sun.com tuttorial site, but I got not much idea).

The problem area in the current code is commented with //// ??????????????????????????????????.
I feel a little shameless to ask you for help again with my half-cooked code. But I would like you to know that I am spending quite much time everyday trying to learn.

Hope you experts may kindly help me again.

Thanks a lot as always!

duta


_______________________________  Here is My Current  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 PhoneBill2 extends JApplet
{
   
  private JPanel Pname;
  private JPanel Pusage;
  private JPanel Ptotal;
  private JPanel Pbutton;
 
 
  /////////////////
 
  private JRadioButton unlimited, limited;
  private ButtonGroup radioGroup;
  ///////////////
 
 
  private JTextField Fname;
  private JTextField Fusage;
  private JTextField Ftotal;
  private Container c = getContentPane ( );
 
  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 ()
  {
   final int numButtons = 2;
   JRadioButton[] radioButtons = new JRadioButton [numButtons];
   final ButtonGroup group = new ButtonGroup ();
   
   radioButtons[0] = new JRadioButton ("Unlimited Plan:", true );
   radioButtons[1] = new JRadioButton ("300 Anytime Minutes", false);
   
   for ( int i = 0; i < numButtons; i++ )
   {
     group.add (radioButtons [i] );
   }
 
   // select the first button by default
   radioButtons[0].setSelected (true);
 }
 /////  ?????????????????????????????????????????????????????????????????
  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.");
     }
         
    }
 }
}    

0
Comment
Question by:duta
  • 6
  • 5
11 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 17980758
JComboBox choices = new JComboBox(new Object[] { "Unlimited Plan", "300 Anytime Minutes" });
0
 

Author Comment

by:duta
ID: 17980794
Thanks a lot, CEHJ.

Can you kindly check other parts ofthe code which is related to the ComboBox, particualrly class ButtonLister toward the end of the code?

Thanks again!
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 17980809
If you called the combo 'planList' it could be left as is
0
Simplifying Server Workload Migrations

This use case outlines the migration challenges that organizations face and how the Acronis AnyData Engine supports physical-to-physical (P2P), physical-to-virtual (P2V), virtual to physical (V2P), and cross-virtual (V2V) migration scenarios to address these challenges.

 

Author Comment

by:duta
ID: 17980891
CEHJ, thanks a lot for your kind help.

I am not sure whether I corrected as you intended. When I ran the applet, the plan combobox did not show up.

Would you kindly check my latest code below?  Thanks again!

____________________  Latest 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 PhoneBill2 extends JApplet
{
   
  private JPanel Pname;
  private JPanel Pusage;
  private JPanel Ptotal;
  private JPanel Pbutton;
 
 
  /////////////////
 
  private JRadioButton unlimited, limited;
  private ButtonGroup radioGroup;
  ///////////////
 
 
  private JTextField Fname;
  private JTextField Fusage;
  private JTextField Ftotal;
  private Container c = getContentPane ( );
 
 // 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 ()
  {
   
  JComboBox plans = new JComboBox(new Object[] { "Unlimited Plan", "300 Anytime Minutes" });  
   
 
   // select the first button by default
   plans.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.");
     }
         
    }
 }
}    
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 17980917
You didn't add it to your GUI ...

And you didn't name it 'planList' so your listening code will break. You should make planList an instance variable too, not a local one
0
 

Author Comment

by:duta
ID: 17980999
CEHJ, thanks again for your kind, prompt response.

I am not sure whether I fully followed your instructions. But still plan combobox did not show up yet.
Would  you kindly check my latest code below?  Thanks a lot!

duta

_______________________________ Latest 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 PhoneBill2 extends JApplet
{
  private JList planList;
  private JPanel Pname;
  private JPanel Pusage;
  private JPanel Ptotal;
  private JPanel Pbutton;
 
 
  /////////////////
 
  private JRadioButton unlimited, limited;
  private ButtonGroup radioGroup;
  ///////////////
 
 
  private JTextField Fname;
  private JTextField Fusage;
  private JTextField Ftotal;
  private Container c = getContentPane ( );
 
 // private String plans [] = {"Unlimited Plan", "Limited Plan"};
  JComboBox plans = new JComboBox(new Object[] { "Unlimited Plan", "300 Anytime Minutes" });
 
  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 ()
  {
   
   
   
 
   // select the first button by default
   plans.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.");
     }
         
    }
 }
}    
0
 
LVL 86

Accepted Solution

by:
CEHJ earned 500 total points
ID: 17981059
Change

>>private JList planList;

to


  JComboBox planList; = new JComboBox(new Object[] { "Unlimited Plan", "300 Anytime Minutes" });
0
 

Author Comment

by:duta
ID: 17981183
CEHJ, it is working after putting private in front of JComboBox planList = new JComboBox(new Object[] { "Unlimited Plan", "300 Anytime Minutes" });

I think you did all you could do. I am going to accept your tip as acceptable solution.

But if you do not mind, can you let me how to custom-size the combobox? It is displayed too long.

Thanks a lot!


0
 
LVL 86

Expert Comment

by:CEHJ
ID: 17981213
Well its size depends on the layout manager used. Since you're adding it to a GridLayout, it will expand to fit the available width
0
 

Author Comment

by:duta
ID: 17981234
Thanks a lot for yur great tip. I may post it as a separate question soon.

Hope you may come back to help me again!

duta

0
 
LVL 86

Expert Comment

by:CEHJ
ID: 17981286
:-)
0

Featured Post

ScreenConnect 6.0 Free Trial

Want empowering updates? You're in the right place! Discover new features in ScreenConnect 6.0, based on partner feedback, to keep you business operating smoothly and optimally (the way it should be). Explore all of the extras and enhancements for yourself!

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
micro services spring boot application error 3 197
jdbc error in jsp application 20 46
MySqlDump not dumping triggers 1 31
how to install java on RHEL image on EC2 4 28
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
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:

809 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