Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

Java Swing: How to convert Combobox to Radio Button?

Posted on 2006-11-20
24
Medium Priority
?
678 Views
Last Modified: 2013-11-23
Hi experts again!

I got a simple working code to calculate phone bill from the user input.

I would like to learn how to convert combobox ( to choose phone plans) in my code into JCheckBox.

Hope you may kindly help me again!  I am a total novice in java Swing.

Thanks a lot!

duta

______________________  Here is my half-cooked 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 PhoneBill4 extends JApplet
{
 // private JList planList;
 //private JComboBox planList = new JComboBox(new Object[] { "Unlimited Plan", "300 Anytime Minutes" });
 
  private JCheckBox unlimited, limited;  // to create two checkboxes
  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"};
  // JCheckBox plans = new JCheckBox(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 ()
  {
   
   unlimited = new JCheckBox ("Unlimited");
   limited = new JCheckBox ("Limited");
   c.add (unlimited);
   c.add (limited);
   
 
   // 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
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
  • 13
  • 6
  • 5
24 Comments
 
LVL 10

Assisted Solution

by:ADSLMark
ADSLMark earned 1600 total points
ID: 17981833
I think you want to use JRadioButtons instead:

Replace:
// private String plans [] = {"Unlimited Plan", "Limited Plan"};
// JCheckBox plans = new JCheckBox(new Object[] { "Unlimited Plan", "300 Anytime Minutes" });

=>
private JRadioButton jrbUnlimited;
private JRadioButton jrbLimited;

Replace:
unlimited = new JCheckBox ("Unlimited");
limited = new JCheckBox ("Limited");
=>
jrbUnlimited = new JRadioButton("Unlimited");
jrbUnlimited.setSelected(true);
jrbLimited = new JRadioButton("Limited");
ButtonGroup group = new ButtonGroup();
group.add(jrbUnlimited);
group.add(jrbLimited);

Replace:
c.add (unlimited);
c.add (limited);
=>
JPanel radioPanel = new JPanel(new GridLayout(0, 1));
radioPanel.add(jrbUnlimited);
radioPanel.add(jrbLimited);
c.add(radioPanel);

Replace:
plan = planList.getSelectedIndex ();
if (plan==1 )
=>
if(jrbUnlimited.isSelected())

I hope it's clear. Anyway, i decided to clean your code:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class RadioExample extends JApplet
{
    private JTextField tfName;
    private JTextField tfUsage;
    private JTextField tfTotal;
    private JRadioButton rbUnlimited;
    private JRadioButton rbLimited;

    public void init()
    {
        //Build user interface
        Container c = this.getContentPane();
        c.setLayout(new GridLayout(5, 1));
        c.add(buildPlan());
        c.add(buildName());
        c.add(buildUsage());
        c.add(buildTotal());
        c.add(buildButton());
    }

    private JPanel buildPlan()
    {
        JPanel pnl = new JPanel();

        //Create radio buttons
        rbUnlimited = new JRadioButton("Unlimited");
        rbLimited = new JRadioButton("Limited");

        //Set default
        rbUnlimited.setSelected(true);

        //Add to the same group
        ButtonGroup rbGroup = new ButtonGroup();
        rbGroup.add(rbUnlimited);
        rbGroup.add(rbLimited);

        //Add to panel
        pnl.add(rbUnlimited);
        pnl.add(rbLimited);

        return pnl;
    }

    private JPanel buildName()
    {
        JPanel pnl = new JPanel();

        //Create textfield
        tfName = new JTextField(20);

        //Add to panel
        pnl.setLayout(new FlowLayout(FlowLayout.RIGHT));
        pnl.add(new JLabel("Your Name: "));
        pnl.add(tfName);

        return pnl;
    }

    private JPanel buildUsage()
    {
        JPanel pnl = new JPanel();

        //Create textfield
        tfUsage = new JTextField(20);

        //Add to panel
        pnl.setLayout(new FlowLayout(FlowLayout.RIGHT));
        pnl.add(new JLabel("Your Anytime Usage: "));
        pnl.add(tfUsage);

        return pnl;
    }

    private JPanel buildTotal()
    {
        JPanel pnl = new JPanel();

        //Create textfield
        tfTotal = new JTextField(20);
        tfTotal.setEditable(false);

        //Add to panel
        pnl.setLayout(new FlowLayout(FlowLayout.RIGHT));
        pnl.add(new JLabel("Your Total Charge: "));
        pnl.add(tfTotal);

        return pnl;
    }

    private JPanel buildButton()
    {
        JPanel pnl = new JPanel();

        //Create textfield
        JButton btnCalc = new JButton("Calculate");
        btnCalc.addActionListener(new ButtonListener());

        //Add to panel
        pnl.add(btnCalc);

        return pnl;
    }

    //Listener
    private class ButtonListener implements ActionListener
    {
        public void actionPerformed(ActionEvent e)
        {
            String name = tfName.getText();

            try
            {
                int mins_used = Integer.parseInt(tfUsage.getText());

                if(rbUnlimited.isSelected())
                {
                    if(mins_used <= 300)
                    {
                        float total = 69.99f;
                        tfTotal.setText(""+total);
                    }
                    else
                    {
                        float total = 39.99f + ((mins_used - 300) * 0.45f);
                        tfTotal.setText(""+total);
                    }
                }
                else
                {
                    float total = 69.99f;
                    tfTotal.setText(""+total);
                }
            }
            catch(NumberFormatException nfe)
            {
                tfTotal.setText("Please enter an integer by usage.");
            }
        }
    }
}

I hope it works (i tested with JFrame, not JApplet)
Good luck.
Mark
0
 
LVL 10

Expert Comment

by:ADSLMark
ID: 17981837
Whoops class RadioExample should be class PhoneBill4. Sorry.

Mark
0
 

Author Comment

by:duta
ID: 17981933
Mark, you are just wonderful.  

I will take time to make corrections as you kindly instructed.

Thanks again!

duta
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:duta
ID: 17982134
Hi Mark,

I tried your code, and got ssveral error messages.

They include:
(1)
"Cannot find symbol constructor JRadioButton at the line:
rbUnlimited = new JRadioButton ("Unlimited");

(2)

Internal error Cannot initiate JRadioButton. <init> at JRadioButton to ()

(3) cannot find symbol method setSelected ( boolean)


Thank you so much for your kind, great help all along. Your help tremendously help me hang on!

duta

0
 
LVL 10

Expert Comment

by:ADSLMark
ID: 17982246
Sorry, i cannot reproduce the error, are you sure you have the correct imports?

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

JRadioButton is in the package javax.swing.JRadioButton.. so..
Maybe you have a different version of java jdk/jre?

Mark
0
 

Author Comment

by:duta
ID: 17982276
Dear Mark, Thank you so much for your kind, patient help.

Yes, I got the error message from DrJava. I am going to try your code with NetBeans. I am downloading NetBeans.
I will come back in a few minutes with updates.

Thanks again!

duta
0
 

Author Comment

by:duta
ID: 17982344

Dear Mark,  hi again. Hope I am not taking too  much of your time because I am such a novice.

By the way,  I use JDK and JRE 1.5.0._7.

Here are a copy of the error message that I got while trying to compile with netBeans (5.5).

Thanks again!

duta

__________________ Error messages _______________________________

init:
deps-jar:
Compiling 1 source file to C:\Documents and Settings\admim\Desktop\OK\JRadioButton\JRadioButton\build\classes
C:\Documents and Settings\admin\Desktop\OK\JRadioButton\JRadioButton\src\JRadioButton.java:32: cannot find symbol
symbol  : constructor JRadioButton(java.lang.String)
location: class JRadioButton
        rbUnlimited = new JRadioButton("Unlimited");
C:\Documents and Settings\admin\Desktop\OK\JRadioButton\JRadioButton\src\JRadioButton.java:33: cannot find symbol
symbol  : constructor JRadioButton(java.lang.String)
location: class JRadioButton
        rbLimited = new JRadioButton("Limited");
C:\Documents and Settings\admin\Desktop\OK\JRadioButton\JRadioButton\src\JRadioButton.java:36: cannot find symbol
symbol  : method setSelected(boolean)
location: class JRadioButton
        rbUnlimited.setSelected(true);
C:\Documents and Settings\admin\Desktop\OK\JRadioButton\JRadioButton\src\JRadioButton.java:40: add(javax.swing.AbstractButton) in javax.swing.ButtonGroup cannot be applied to (JRadioButton)
        rbGroup.add(rbUnlimited);
C:\Documents and Settings\admin\Desktop\OK\JRadioButton\JRadioButton\src\JRadioButton.java:41: add(javax.swing.AbstractButton) in javax.swing.ButtonGroup cannot be applied to (JRadioButton)
        rbGroup.add(rbLimited);
C:\Documents and Settings\admin\Desktop\OK\JRadioButton\JRadioButton\src\JRadioButton.java:121: cannot find symbol
symbol  : method isSelected()
location: class JRadioButton
                if(rbUnlimited.isSelected())
6 errors
BUILD FAILED (total time: 1 second)
0
 
LVL 10

Expert Comment

by:ADSLMark
ID: 17982708
hmm you named the file JRadioButton.java ?? Please change that to RadioExample.java, i hope that helps?

Mark
0
 

Author Comment

by:duta
ID: 17982841
Dear Mark, thanks again for your kind response.

I changed the class name as you kindly suggested, but I got the same error message.

It seems that JRadioButton is not properly recognized. I wonder wehter I may need to import some other packages to get JRadioButton recognized.

Thanks a lot!

duta
0
 
LVL 10

Expert Comment

by:ADSLMark
ID: 17982942
I have truly no idea why you are missing the JRadioButton. It is in the package javax.swing, ie. javax.swing.JRadioButton. Just make sure that all your imports are correct, the swing libraries is installed (should be default with java nowadays) and that you have no weird naming problems (duplicate names or similar). You can also create a VERY small test class:

import javax.swing.JRadioButton;
public class MyTestExample
{
   JRadioButton b1;
   JRadioButton b2;
   public MyTestExample()
  {
    this.b1 = new JRadioButton();
    this.b2 = new JRadioButton("with text");
  }
}

It won't run, but it should compile.
Mark
0
 
LVL 26

Expert Comment

by:ksivananth
ID: 17983577
clear the output directory!
also make sure, you have javax.swing.* as imported
0
 

Author Comment

by:duta
ID: 17983752
Mark, your MyTestExample compiled without any trouble.
ksivananth, I removed all  existing .class files in the same  folder as my code is.

After all these, still the code showed the same error message.

I am so grateful to all of you for trying to help this novice so patiently.

duta




0
 
LVL 26

Accepted Solution

by:
ksivananth earned 400 total points
ID: 17983793
replace JRadioButton with javax.swing.JRadioButton in all the place and then check!
0
 

Author Comment

by:duta
ID: 17983896
ksivanath, your tip is working. Thanks a lot!

I am going to accept Mark's tip as acceptable solution and  ksivanath's as assisted.

Thanks a lot for your kind, patient help.  My special thanks goes to Mark who spent tons of time for me this afternoon.

duta
0
 

Author Comment

by:duta
ID: 17983936
I think I made a wrong button. I need to correct this asap.

I intended to accept Mark's as acceptable solution and ksinvanath as assisted.

I am going to cotntact moderator asasp.
I am so sorry for this.
0
 

Author Comment

by:duta
ID: 17983960
TO: Moderator:

I made a mistake in accepting the solution.

Where should I go to make the correction?

I intended to award 400 pts to Mark and 100 pts to  ksivananth.

Thanks!
0
 
LVL 26

Expert Comment

by:ksivananth
ID: 17983968
if my tip is working, then the problem is with you have not cleared the output directory clearly!

or somehow the old .class file is existing and set in classpath!
0
 
LVL 26

Expert Comment

by:ksivananth
ID: 17983989
>>I intended to award 400 pts to Mark and 100 pts to  ksivananth.

this is done as intended!
0
 

Author Comment

by:duta
ID: 17984035
ksvananth, thank you so much for your kind, prompt response.

I am so sorry to tell you, but I also intended to accept Mark's as acceptable solution because I asked:
Title: Java Swing: How to convert Combobox to Radio Button?".

Thanks again!
0
 
LVL 26

Expert Comment

by:ksivananth
ID: 17984076
you are right!

I just mentioned that one of your intend is done already and only the other one( changing the answer state ) is required!
0
 

Author Comment

by:duta
ID: 17984117
ksvananth, can you kindly let me know how to make the change? I tried to find a helpful link, but I couldn't.

Thanks again!
0
 
LVL 26

Expert Comment

by:ksivananth
ID: 17984131
I am not sure exactly but you may post a 0 point question in http://www.experts-exchange.com/Community_Support/
0
 

Author Comment

by:duta
ID: 17984135
TO: Moderator:

Please make a change so that Mark's tip becomes the acceptable solution (400pts) and ksivananth's as assisted tip (100 pts).

If you make the correction as soon as possible, I will truly appreciate.  Using this opportunity, I would like to extend my deep apology to Mark for my horrible mistake.

Thanks all!

duta
0
 

Author Comment

by:duta
ID: 17984171
ksinvananth, thanks again for your kindness. I went to the site and left a message asking for the change I wanted.

duta
0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Question has a verified solution.

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

Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.
Suggested Courses

618 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