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.
Code :
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();
}
}
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.
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.
Code :
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;
}
}
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.
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?
Re: Event Listener for ComboBox
Quote:
Originally Posted by
JamesdTurnham
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.
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.
Re: Event Listener for ComboBox
Quote:
Originally Posted by
JamesdTurnham
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.
Quote:
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.
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.
Code :
/* 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();
}
}