I have the main part of my code done but I don'T know if I should use an action listener or an event listener for my JComboBox. I have 4 JComboBoxes and only need to retrieve the info from my vehicleBox and fuelBox at this point. I need to take that information and make it equal the value I aleady have declared it and use it to figure out the total cost of a trip. I am a beginner at programming so if any help that you can give, please dumb it down to a level a beginner would understand. Thanks for any help you can offer.

Here is the code i have so far:

import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.text.*;
import java.util.*;


public class TravelerGasolineCalculator extends JFrame implements ActionListener, EventListener
{
    //declare variables
    int totalMiles, mpg;
    double oilChange = 30.00, fuelCost, totalCost, costPerMile, fuel, total, numOfGallons;
    double superUnleadedCost=3.00, unleadedCost=2.90, leadedCost=2.50, dieselCost=4.00;
    int compactTank=13,midSizeTank=18, luxuryTank=15,suvTank=23;
    String location[] = {"New York, NY","Minneapolis, MN", "Boise, ID", "Dallas, TX", "Miami, FL", "Las Vegas, NV"};
    String locationTwo[] = {"New York, NY","Minneapolis, MN", "Boise, ID", "Dallas, TX", "Miami, FL", "Las Vegas, NV"};
    String vehicle[] = {"Compact", "Mid-Size", "Luxury", "SUV"};
    String fuelPrice[] = {"Leaded", "Unleaded", "Super Unleaded", "Diesel"};

    //COnstruct a panel for each row
    JPanel firstRow = new JPanel();
    JPanel secondRow = new JPanel();
    JPanel thirdRow = new JPanel();
    JPanel fourthRow = new JPanel();
    JPanel fifthRow = new JPanel();
    JPanel sixthRow = new JPanel();
    JPanel seventhRow = new JPanel();
    JPanel eighthRow = new JPanel();
    JPanel ninthRow = new JPanel();
    JPanel tenthRow = new JPanel();


    //Construct a panel for the fields and button
    JPanel fieldPanelOne = new JPanel();
    JPanel fieldPanelTwo = new JPanel();
    JPanel buttonPanelOne = new JPanel();
    JPanel buttonPanelTwo = new JPanel();

    //Construct labels and texts boxes
    JLabel milesLabel = new JLabel("Anticipated Miles:");
        JTextField miles = new JTextField(10);
    JLabel costPerGallonLabel = new JLabel("Cost Per Gallon");
        JTextField costPerGallon = new JTextField(10);
    JLabel milesPerGallonLabel = new JLabel("Miles Per Gallon");
        JTextField milesPerGallon = new JTextField(10);
    JLabel calcLabel = new JLabel("           Press the Calculate button");
    JLabel beginningLocationLabel = new JLabel("Beginning Location");
        JComboBox cityBox = new JComboBox(location);
    JLabel destinationLabel = new JLabel("Destination");
        JComboBox cityBoxTwo = new JComboBox(locationTwo);
    JLabel vehicleSizeLabel = new JLabel("Vehicle Size");
        JComboBox vehicleBox = new JComboBox(vehicle);
    JLabel fuelLabel = new JLabel("Fuel Type");
        JComboBox fuelBox = new JComboBox(fuelPrice);
    JLabel submitLabel = new JLabel("Press the Submit Button");



    // Construct button
    JButton calcButton = new JButton("Calculate");
    JButton submitButton = new JButton("Submit");
    JButton clearButton = new JButton("Clear");

    public static void main(String[] args)
    {
        //set the look of the interface
        try
        {
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
        }
        catch(Exception e)
        {
            JOptionPane.showMessageDialog(null,"The Traveler's Gasoline Calculator could not set the Look and Feel.","Error", JOptionPane.INFORMATION_MESSAGE);
        }

        TravelerGasolineCalculator f = new TravelerGasolineCalculator();
        f.setSize(450,400);
        f.setTitle("Traveler's Gasoline Calculator");
        f.setResizable(true);
        f.setLocation(200,200);
        f.setVisible(true);
    }

    public TravelerGasolineCalculator()
    {
        Container c = getContentPane();
        c.setLayout((new BorderLayout()));
        fieldPanelOne.setLayout(new GridLayout(4,2));
        FlowLayout rowSetup = new FlowLayout(FlowLayout.LEFT,5,3);
            firstRow.setLayout(rowSetup);
            secondRow.setLayout(rowSetup);
            thirdRow.setLayout(rowSetup);
            fourthRow.setLayout(rowSetup);
        fieldPanelTwo.setLayout(new GridLayout(5,2));
            fifthRow.setLayout(rowSetup);
            sixthRow.setLayout(rowSetup);
            seventhRow.setLayout(rowSetup);
            eighthRow.setLayout(rowSetup);
            ninthRow.setLayout(rowSetup);
            tenthRow.setLayout(rowSetup);
        buttonPanelOne.setLayout(new FlowLayout(FlowLayout.CENTER));

        //Add Fields to rows
        firstRow.add(milesLabel);
        firstRow.add(miles);

        secondRow.add(costPerGallonLabel);
        secondRow.add(costPerGallon);

        thirdRow.add(milesPerGallonLabel);
        thirdRow.add(milesPerGallon);

        fourthRow.add(calcLabel);

        fifthRow.add(beginningLocationLabel);
        fifthRow.add(cityBox);

        sixthRow.add(destinationLabel);
        sixthRow.add(cityBoxTwo);

        seventhRow.add(vehicleSizeLabel);
        seventhRow.add(vehicleBox);

        eighthRow.add(fuelLabel);
        eighthRow.add(fuelBox);

        ninthRow.add(submitLabel);


        //Adds rows to panel
        fieldPanelOne.add(firstRow);
        fieldPanelOne.add(secondRow);
        fieldPanelOne.add(thirdRow);
        fieldPanelOne.add(fourthRow);
        fieldPanelTwo.add(fifthRow);
        fieldPanelTwo.add(sixthRow);
        fieldPanelTwo.add(seventhRow);
        fieldPanelTwo.add(eighthRow);
        fieldPanelTwo.add(ninthRow);

        //adds button to panel
        buttonPanelOne.add(calcButton);
        buttonPanelOne.add(submitButton);
        buttonPanelOne.add(clearButton);

        //Adds panels to frame
        c.add(fieldPanelOne, BorderLayout.NORTH);
        c.add(fieldPanelTwo, BorderLayout.CENTER);
        c.add(buttonPanelOne, BorderLayout.SOUTH);

        //adds funtion to buttons
        calcButton.addActionListener(this);
        submitButton.addActionListener(this);
        clearButton.addActionListener(this);

        //adds function to dropdown lists
        cityBox.addActionListener(this);
        cityBoxTwo.addActionListener(this);
        vehicleBox.addActionListener(this);
        fuelBox.addActionListener(this);

    }

    public void actionPerformed(ActionEvent e)
    {
        //Calculates total cost with or without an oil change
        fuel = Double.parseDouble (costPerGallon.getText());
        mpg = Integer.parseInt (milesPerGallon.getText());
        total = Double.parseDouble (miles.getText());
        numOfGallons = total/mpg;
        totalCost = numOfGallons*fuel;
        costPerMile = totalCost/total;

        DecimalFormat twoDigit = new DecimalFormat("$#,###.##");

                if (total < 3000)
                {
                    JOptionPane.showMessageDialog(null,"Your approximate cost of the trip is " + twoDigit.format(totalCost) + ".","Approximate Cost",JOptionPane.INFORMATION_MESSAGE);
                }

                else
                {
                    totalCost = numOfGallons * fuel + oilChange;
                    costPerMile = totalCost/total;

                    JOptionPane.showMessageDialog(null,"Your total cost of the trip is " + twoDigit.format(totalCost) + ".","Cost With Oil Change", JOptionPane.INFORMATION_MESSAGE);
                }
    }

     public void itemStateChanged(ItemEvent ie)
     {
     }

}

Dani AI

Generated

Short answer: if the vehicle and fuel choices are only needed when the user clicks Submit, do not attach listeners to every JComboBox. Read the combo values inside the Submit button’s ActionListener and keep the rest of the UI simple — this keeps the logic easy to follow and avoids extra events. This matches ’s point (it depends on when you need the action) and the direction started you toward: pull the combo selections when you actually perform the calculation. (docs.oracle.com)

If the UI must react immediately when the user changes a selection (for example update a preview or enable/disable controls), use an ItemListener and filter for the SELECTED state. ItemListeners can deliver both DESELECTED and SELECTED events when the selection changes, so test ItemEvent.getStateChange() and only act on SELECTED to avoid doing work twice. The Java tutorial and ItemEvent javadoc show this pattern. (docs.oracle.com)

ActionListeners on JComboBox are also valid: an ActionEvent is sent when a selection is made (and when programmatic selection methods are called), but it gives you a less granular signal than ItemListener. If both listener types are registered you can get overlapping notifications, so pick one approach per combo and avoid duplicate handling. StackOverflow and the Javadoc discuss these tradeoffs. (docs.oracle.com)

A few practical, beginner-friendly fixes for your code: remove the unrelated EventListener from your class signature (use ItemListener only if you implement itemStateChanged), dispatch actions inside actionPerformed by checking e.getSource() so Submit/Calculate/Clear are handled separately, and add input validation (catch NumberFormatException) before parsing numbers. Also build the GUI on the Swing Event Dispatch Thread (SwingUtilities.invokeLater) to avoid subtle threading bugs. These small changes will make the program more robust and much easier to maintain. (docs.oracle.com)

Recommended Answers

All 2 Replies

depends on the action on which you want something performed. when selecting a new value in a dropdownlist? after clicking a button? after typing a character in a textfield?

I think you can get the content of combobox by using following things.

public void actionPerformed(ActionEvent e) {
        JComboBox cb = (JComboBox)e.getSource();
        String petName = (String)cb.getSelectedItem();

It will retutn the string that you have selected on the combobox.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.