Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 9 of 9

Thread: Event Listener for ComboBox

  1. #1
    Junior Member
    Join Date
    Nov 2012
    Posts
    29
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Event Listener for ComboBox

    I have the code for the JPanel and JComboBox and I want it so that when the user selects "Compact" from the combobox it the code then inputs 25 into a MPG variable and does it's calculations. The problem is that I don't know how to code the select option. I've read various tutorials but I can't find anything similar.

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.text.*;
     
     
    public class TripCalc extends JFrame implements ActionListener
    {  
       int mpg;
     
     
     
       //construct components
       JLabel typePrompt = new JLabel("Vehicle Type");
       JComboBox typeCombo = new javax.swing.JComboBox();
       JTextPane typePane = new JTextPane();
     
       JLabel fuelPrompt = new JLabel("Fuel Type");
       JComboBox fuelCombo = new javax.swing.JComboBox();
       JTextPane fuelPane = new JTextPane();
     
       JLabel beginningPrompt = new JLabel("Starting Location");
       JComboBox startCombo = new javax.swing.JComboBox();
       JTextPane startPane = new JTextPane();
     
       JLabel endPrompt = new JLabel("Ending Location");
       JComboBox endCombo = new javax.swing.JComboBox();
       JTextPane endPane = new JTextPane();
     
     
     
        // Panel Creation
        JPanel firstRow = new JPanel();
        JPanel secondRow = new JPanel();
     
        // Panel for Fields and Buttons
        JPanel fieldPanel = new JPanel();
        JPanel buttonPanel = new JPanel();
     
        // Construct Labels and TextBoxes
        JLabel Miles = new JLabel("Miles planning to travel"         );
          JTextField distance = new JTextField(5);
        JLabel Fuelcost = new JLabel("What is the price per gallon?"              );
          JTextField fuelprice = new JTextField(3);
        JLabel Total = new JLabel("Your total cost for the trip will be"            );
          JTextField totalcost = new JTextField(6);
        JButton submitButton = new JButton("Submit"); 
        JButton clearButton = new JButton("Clear Fields");
     
      //create the content pane
      public Container createContentPane()
      {
        //populate the JCombobox
        typeCombo.addItem("Compact");
        typeCombo.addItem("Mid-Size");
        typeCombo.addItem("Luxury");
        typeCombo.addItem("SUV");
        typeCombo.addActionListener(this);
     
        fuelCombo.addItem("Leaded");
        fuelCombo.addItem("Unleaded");
        fuelCombo.addItem("Super Unleaded");
        fuelCombo.addItem("Diesel");
        fuelCombo.addActionListener(this);
     
        startCombo.addItem("Minneapolis");
        startCombo.addItem("Duluth");
        startCombo.addItem("Bemidji");
        startCombo.addItem("Rochester");
        startCombo.addItem("Detroit Lakes");
        startCombo.addItem("St.Cloud");
        startCombo.addActionListener(this);
     
        endCombo.addItem("Daytona");
        endCombo.addItem("Darlington");
        endCombo.addItem("Las Vegas");
        endCombo.addItem("Talladega");
        endCombo.addItem("Richmond");
        endCombo.addItem("Bristol");
        endCombo.addActionListener(this);
     
        //construct and populate the north panel
        JPanel northPanel = new JPanel();
        northPanel.setLayout(new FlowLayout());
        northPanel.add(typePrompt);
        northPanel.add(typeCombo);                  
        northPanel.add(fuelPrompt);
        northPanel.add(fuelCombo);
        northPanel.add(beginningPrompt);
        northPanel.add(startCombo);
        northPanel.add(endPrompt);
        northPanel.add(endCombo);
     
        JPanel southPanel = new JPanel();
        southPanel.setLayout(new FlowLayout());
        southPanel.add(submitButton);
        southPanel.add(clearButton);
     
        JPanel centerPanel = new JPanel();
        centerPanel.setLayout(new FlowLayout());
        centerPanel.add(Miles);
        centerPanel.add(distance);
        centerPanel.add(Fuelcost);
        centerPanel.add(fuelprice);
        centerPanel.add(Total);
        centerPanel.add(totalcost);
     
     
         //createContainer and set attributes
         Container f = getContentPane();
         setLayout(new BorderLayout(40,40));
         fieldPanel.setLayout(new GridLayout(1,1));
         buttonPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
         add(northPanel,BorderLayout.NORTH);
         add(southPanel,BorderLayout.SOUTH);
         add(centerPanel,BorderLayout.CENTER);
         setLocation(200,200);
         return f;
         }
         //main method executes at run time
         public static void main(String args[])
         {
           TripCalc f = new TripCalc();
           f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
           f.setContentPane(f.createContentPane());
           f.setTitle("Trip Calculator"); 
           f.setSize(800,300);
           f.setVisible(true);
         }  
     
     
         // event to process user clicks
         public void actionPerformed(ActionEvent e)
         {
           String arg = e.getActionCommand();
         }
     
     
    }


  2. #2
    Super Moderator curmudgeon's Avatar
    Join Date
    Aug 2012
    Posts
    1,130
    My Mood
    Cynical
    Thanks
    64
    Thanked 140 Times in 135 Posts

    Default Re: Event Listener for ComboBox

    This tutorial: How to Use Combo Boxes (The Java™ Tutorials > Creating a GUI With JFC/Swing > Using Swing Components)

    has just what you need, a "handling events" section. I suggest that you read it or re-read it and give its recommendations a try.

    --- Update ---

    This tutorial: How to Use Combo Boxes (The Java™ Tutorials > Creating a GUI With JFC/Swing > Using Swing Components)

    has just what you need, a "handling events" section. I suggest that you read it or re-read it and give its recommendations a try.

  3. #3
    Junior Member
    Join Date
    Nov 2012
    Posts
    29
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Event Listener for ComboBox

    I sat around after I posted this and got it to work somewhat. I had a option message box appear and it would always give me a 0 or a 0.0

    Also when I do the calculations I need to convert from text to digits to perform the calculations.

    I think I covered the problems I am still having.

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.text.*;
    import java.math.*;
     
     
    public class TripCalc extends JFrame implements ActionListener
    {  
       int mpg;
       double fuel;
     
     
     
       //construct components
       JLabel typePrompt = new JLabel("Vehicle Type");
       JComboBox typeCombo = new javax.swing.JComboBox();
       JTextPane typePane = new JTextPane();
     
       JLabel fuelPrompt = new JLabel("Fuel Type");
       JComboBox fuelCombo = new javax.swing.JComboBox();
       JTextPane fuelPane = new JTextPane();
     
       JLabel beginningPrompt = new JLabel("Starting Location");
       JComboBox startCombo = new javax.swing.JComboBox();
       JTextPane startPane = new JTextPane();
     
       JLabel endPrompt = new JLabel("Ending Location");
       JComboBox endCombo = new javax.swing.JComboBox();
       JTextPane endPane = new JTextPane();
     
     
     
        // Panel Creation
        JPanel firstRow = new JPanel();
        JPanel secondRow = new JPanel();
     
        // Panel for Fields and Buttons
        JPanel fieldPanel = new JPanel();
        JPanel buttonPanel = new JPanel();
     
        // Construct Labels and TextBoxes
        JLabel Miles = new JLabel("Miles planning to travel"         );
          JTextField distance = new JTextField(5);
        JLabel Fuelcost = new JLabel("What is the price per gallon?"              );
          JTextField fuelprice = new JTextField(3);
        JLabel Total = new JLabel("Your total cost for the trip will be"            );
          JTextField totalcost = new JTextField(6);
        JButton submitButton = new JButton("Submit"); 
        JButton clearButton = new JButton("Clear Fields");
     
      //create the content pane
      public Container createContentPane()
      {
        //populate the JCombobox
        typeCombo.addItem("Compact");
        typeCombo.addItem("Mid-Size");
        typeCombo.addItem("Luxury");
        typeCombo.addItem("SUV");
        typeCombo.addActionListener(this);
     
        fuelCombo.addItem("Leaded");
        fuelCombo.addItem("Unleaded");
        fuelCombo.addItem("Super Unleaded");
        fuelCombo.addItem("Diesel");
        fuelCombo.addActionListener(this);
     
        startCombo.addItem("Minneapolis");
        startCombo.addItem("Duluth");
        startCombo.addItem("Bemidji");
        startCombo.addItem("Rochester");
        startCombo.addItem("Detroit Lakes");
        startCombo.addItem("St.Cloud");
        startCombo.addActionListener(this);
     
        endCombo.addItem("Daytona");
        endCombo.addItem("Darlington");
        endCombo.addItem("Las Vegas");
        endCombo.addItem("Talladega");
        endCombo.addItem("Richmond");
        endCombo.addItem("Bristol");
        endCombo.addActionListener(this);
     
        //construct and populate the north panel
        JPanel northPanel = new JPanel();
        northPanel.setLayout(new FlowLayout());
        northPanel.add(typePrompt);
        northPanel.add(typeCombo);                  
        northPanel.add(fuelPrompt);
        northPanel.add(fuelCombo);
        northPanel.add(beginningPrompt);
        northPanel.add(startCombo);
        northPanel.add(endPrompt);
        northPanel.add(endCombo);
     
        JPanel southPanel = new JPanel();
        southPanel.setLayout(new FlowLayout());
        southPanel.add(submitButton);
        southPanel.add(clearButton);
     
        JPanel centerPanel = new JPanel();
        centerPanel.setLayout(new FlowLayout());
        centerPanel.add(Miles);
        centerPanel.add(distance);
        centerPanel.add(Fuelcost);
        centerPanel.add(fuelprice);
        centerPanel.add(Total);
        centerPanel.add(totalcost);
     
     
         //createContainer and set attributes
         Container f = getContentPane();
         setLayout(new BorderLayout(40,40));
         fieldPanel.setLayout(new GridLayout(1,1));
         buttonPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
         add(northPanel,BorderLayout.NORTH);
         add(southPanel,BorderLayout.SOUTH);
         add(centerPanel,BorderLayout.CENTER);
         setLocation(200,200);
         return f;
         }
         //main method executes at run time
         public static void main(String args[])
         {
           TripCalc f = new TripCalc();
           f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
           f.setContentPane(f.createContentPane());
           f.setTitle("Trip Calculator"); 
           f.setSize(800,300);
           f.setVisible(true);
         }  
     
     
         // event to process user clicks
         public void actionPerformed(ActionEvent e)
         {
           String arg = e.getActionCommand();
           if (e.getSource()=="Compact") mpg = 25;
           else if (e.getSource()=="Mid-Size") mpg = 19;
           else if (e.getSource()=="Luxury") mpg = 17;
           else if (e.getSource()=="SUV") mpg = 15;
           else if (e.getSource()=="Leaded") fuel = 3.99;
           else if (e.getSource()=="Unleaded") fuel = 3.19;
           else if (e.getSource()=="Super Unleaded") fuel = 3.99;
           else if (e.getSource()=="Diesel") fuel = 4.19;
     
           totalcost = (distance / mpg) * fuel; 
     
         }
     
     
    }

  4. #4
    Super Moderator curmudgeon's Avatar
    Join Date
    Aug 2012
    Posts
    1,130
    My Mood
    Cynical
    Thanks
    64
    Thanked 140 Times in 135 Posts

    Default Re: Event Listener for ComboBox

    Your current code won't compile.

    But looking over it, I wonder why you're even adding listeners to the JComboBoxes. Why not simply leave them alone as there is no need for them to do anything when the user selects an item in them other than their natural behavior of changing the displayed selection. Instead, I believe all of your actions should be initiated when the submit JButton is pressed and only when that button is pressed. Consider giving that JButton an ActionListener that first checks to make sure that no JTextField is left blank, and then have it extract all the information it needs from the JComboBoxes and JTextFields, and then use this information to calculate what you want to calculate.

    Note that you can parse a String into an int using Integer.parseInt(String text). The method will return an int that represents the String passed in or it will throw a NumberFormatException if the String passed in is not a valid String representation of an int.

  5. #5
    Junior Member
    Join Date
    Nov 2012
    Posts
    29
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Event Listener for ComboBox

    I understand what your saying but the next question is how to implement it. I presume I assign each of the JComboBox options a defined variable and then use that for the calculations?

  6. #6
    Super Moderator curmudgeon's Avatar
    Join Date
    Aug 2012
    Posts
    1,130
    My Mood
    Cynical
    Thanks
    64
    Thanked 140 Times in 135 Posts

    Default Re: Event Listener for ComboBox

    Quote Originally Posted by JamesdTurnham View Post
    I understand what your saying but the next question is how to implement it. I presume I assign each of the JComboBox options a defined variable and then use that for the calculations?
    No, no need for that at all, and in fact that would get you the wrong result. Assuming that you've given your submit JButton an ActionListener, inside of that listener's actionPerformed method you go through each JComboBox and extract the selected String, then use that information to do your calculations. The key here is that by doing this you query the JComboBox for its selection only when the button has been pressed.

  7. #7
    Junior Member
    Join Date
    Nov 2012
    Posts
    29
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Event Listener for ComboBox

    How do I tell the program in the actionPerformed method to go through each JComboBox? Also if I put the action listener in the "construction box" I get compiling errors. When I add the actionListener in the eventHandler method I don't get any compiling errors.

  8. #8
    Super Moderator curmudgeon's Avatar
    Join Date
    Aug 2012
    Posts
    1,130
    My Mood
    Cynical
    Thanks
    64
    Thanked 140 Times in 135 Posts

    Default Re: Event Listener for ComboBox

    Quote Originally Posted by JamesdTurnham View Post
    How do I tell the program in the actionPerformed method to go through each JComboBox?
    You simply call methods on the JComboBox variables. You know the variables so it shouldn't be hard to extract the selected item from each one.

    Also if I put the action listener in the "construction box" I get compiling errors. When I add the actionListener in the eventHandler method I don't get any compiling errors.
    If you're getting compilation errors that you need help with, please show the code, show the errors, and indicate in some obvious way which lines are causing the errors to occur.

  9. #9
    Junior Member
    Join Date
    Nov 2012
    Posts
    29
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Event Listener for ComboBox

    I've redone my code and have tried to emulate the examples from the Oracle website but I still keep getting errors. Most of them are <identifier> expected. In this case the bolded part is where I am getting a compilation error.

     
    /* Trip Calc Project
     * 
     *
    */
     
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.text.*;
     
     
    public class TripCalc extends JFrame implements ActionListener
    {  
      String[] typeStrings = { "Compact", "Mid-Size", "Luxury", "Suv" };
      String[] fuelStrings = { "Leaded", "Unleaded", "Premium", "Diesel" };
      String[] startStrings = { "Bemidji", "Detroit Lakes", "Duluth", "Minneapolis", "St. Cloud", "Rochester" };
      String[] endStrings = { "Daytona", "Bristol", "Talladega", "Darlington", "Charlotte", "Richmond" };
     
     
       //construct components
       JLabel typePrompt = new JLabel("Vehicle Type");
       JComboBox typeList = new JComboBox(typeStrings);
       [B]combo.addActionListener(this);[/B]
       JTextPane typePane = new JTextPane();
     
       JLabel fuelPrompt = new JLabel("Fuel Type");
       JComboBox fuelList = new JComboBox(fuelStrings);
       JTextPane fuelPane = new JTextPane();
     
     
       JLabel startPrompt = new JLabel("Starting Location");
       JComboBox startList = new JComboBox(startStrings);
       JTextPane startPane = new JTextPane();
     
     
       JLabel endPrompt = new JLabel("Ending Location");
       JComboBox endList = new JComboBox(endStrings);
       JTextPane endPane = new JTextPane();
     
     
     
     
        // Panel Creation
        JPanel firstRow = new JPanel();
        JPanel secondRow = new JPanel();
     
        // Panel for Fields and Buttons
        JPanel fieldPanel = new JPanel();
        JPanel buttonPanel = new JPanel();
     
        // Construct Labels and TextBoxes
        JLabel Miles = new JLabel("Miles planning to travel"         );
          JTextField distance = new JTextField(5);
        JLabel Fuelcost = new JLabel("What is the price per gallon?"              );
          JTextField fuelprice = new JTextField(3);
        JLabel Total = new JLabel("Your total cost for the trip will be"            );
          JTextField totalcost = new JTextField(6);
        JButton submitButton = new JButton("Submit"); 
        JButton clearButton = new JButton("Clear Fields");
     
     
      //create the content pane
      public Container createContentPane()
      {
     
        //construct and populate the north panel
        JPanel northPanel = new JPanel();
        northPanel.setLayout(new FlowLayout());
        northPanel.add(typePrompt);
        northPanel.add(typeList);                  
        northPanel.add(fuelPrompt);
        northPanel.add(fuelList);
        northPanel.add(startPrompt);
        northPanel.add(startList);
        northPanel.add(endPrompt);
        northPanel.add(endList);
     
        JPanel southPanel = new JPanel();
        southPanel.setLayout(new FlowLayout());
        southPanel.add(submitButton);
        southPanel.add(clearButton);
     
        JPanel centerPanel = new JPanel();
        centerPanel.setLayout(new FlowLayout());
        centerPanel.add(Miles);
        centerPanel.add(distance);
        centerPanel.add(Fuelcost);
        centerPanel.add(fuelprice);
        centerPanel.add(Total);
        centerPanel.add(totalcost);
     
     
     
     
     
         //createContainer and set attributes
         Container f = getContentPane();
         setLayout(new BorderLayout(40,40));
         fieldPanel.setLayout(new GridLayout(1,1));
         buttonPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
     
         add(northPanel,BorderLayout.NORTH);
         add(southPanel,BorderLayout.SOUTH);
         add(centerPanel,BorderLayout.CENTER);
         setLocation(200,200);
         return f;
         }
     
     
     
     
     
         //main method executes at run time
         public static void main(String args[])
         {
           TripCalc f = new TripCalc();
           f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
           f.setContentPane(f.createContentPane());
           f.setTitle("Trip Calculator"); 
           f.setSize(800,300);
           f.setVisible(true);
         }  
     
     
         // event to process user clicks
         public void actionPerformed(ActionEvent e)
         {
           JComboBox typeList = (JComboBox)e.getSource();
           String typeStrings = (String) typeList.getSelectedItem();
     
     
         }
     
     
    }

Similar Threads

  1. Combobox Problem
    By hurleyga in forum AWT / Java Swing
    Replies: 1
    Last Post: December 7th, 2011, 08:55 AM
  2. ComboBox
    By rosebrit3 in forum AWT / Java Swing
    Replies: 1
    Last Post: October 25th, 2011, 12:47 PM
  3. [SOLVED] Populating second combobox from a combobox help!
    By ComputerSaysNo in forum AWT / Java Swing
    Replies: 7
    Last Post: October 18th, 2011, 09:01 AM
  4. do actions in ComboBox
    By java_cs in forum AWT / Java Swing
    Replies: 2
    Last Post: October 1st, 2009, 10:53 AM
  5. Java program to display 2D Array in ComboBox
    By crazydeo in forum AWT / Java Swing
    Replies: 1
    Last Post: May 29th, 2008, 09:13 AM