I cannot get this to show up when I run it and I can't figure out whats wrong.

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

        public class TravelCostEstimator extends Frame implements ActionListener,ItemListener
    {
        //This part defines how the program will look
        Panel partOnePanel = new Panel();
            Label companyLabel = new Label("Traveler's Gasoline Calculator");
            Label milesLabel = new Label("\nAnticipated Miles");
                TextField milesField = new TextField(10);
            Label costPerGallonLabel = new Label("\nAnticipated Per Gallon Cost Of Gas");
                TextField costPerGallonField = new TextField(10);
            Label milesPerGallonLabel = new Label("\nVehicle Miles Per Gallon");
                TextField milesPerGallonField = new TextField(10);
            Button calcButton = new Button("Calculate");
        Panel partTwoPanel = new Panel();
            Label beginningLocationLabel = new Label("\nBeginning Location");
            Label endLocationLabel = new Label("\n Destination");
            Label vehicleSizeLabel = new Label("\n Type of Vehicle");
            Label gasTypeLabel = new Label("\n Type of Gas");
            Button submitButton = new Button("Submit");
            Button clearButton = new Button("Clear");


        //This serves as the main method used by the main class
        public static void main(String[] args)
        {

            TravelCostEstimator f = new TravelCostEstimator();
            f.setBounds(200,200,600,300);
            f.setTitle("Traveler's Gasoline Calculator");
            f.setVisible(true);


            double totalOilChangeCost, totalFuelCost, totalTravelExpense, fuelPrice;
            double oilChangeCost = 30.00;
            double fuelSupeUnleadedCost = 3.00;
            double fuelUnleadedCost = 2.90;
            double fuelLeadedCost = 2.50;
            double fuelDieselCost = 4.00;
            int distanceTravel, milesPerTank, tankCapacity, milesEntered;
            int oilChangeRequired = 3000;
            int vehicleCompactTankCapacity = 13;
            int vehicleMidSizeTankCapacity = 18;
            int vehicleLuxuryTankCapacity = 15;
            int vehicleSUVTankCapacity = 23;
            int totalOilChange = 0;
            char vehicleLabel, fuelLabel, vehicleLabelSelected, fuelLabelSelected;
            int totalMiles, milesPerGallon, mpg;
            double oilChange = 30.00, fuelCost,totalCost, costPerMile, fuel, total, numOfGallons;
        }

        public void init()
        {
            // Sets the layout with two panels
            this.setLayout(new BorderLayout());
                partOnePanel.setLayout(new FlowLayout());
                partTwoPanel.setLayout(new FlowLayout());

            //adds components to partOne panel
            setBackground(Color.red);
            partOnePanel.add(companyLabel);
            partOnePanel.add(milesLabel);
            partOnePanel.add(milesField);
            partOnePanel.add(costPerGallonLabel);
            partOnePanel.add(costPerGallonField);
            partOnePanel.add(milesPerGallonLabel);
            partOnePanel.add(milesPerGallonField);
            partOnePanel.add(calcButton);
                calcButton.addActionListener(this);

            //adds compponents to partTwo panel
            partTwoPanel.add(beginningLocationLabel);
                Choice beginningLocation = new Choice();
                beginningLocation.addItemListener(this);
                    beginningLocation.add("St. Cloud, MN");
                    beginningLocation.add("New York, NY");
                    beginningLocation.add("Dallas, TX");
                    beginningLocation.add("Minneapolis, MN");
                    beginningLocation.add("Las Vegas, NV");
                    beginningLocation.add("Miami, FL");
            partTwoPanel.add(endLocationLabel);
                Choice endLocationChoice = new Choice();
                endLocationChoice.addItemListener(this);
                    endLocationChoice.add("Seattle, WA");
                    endLocationChoice.add("Denver, CO");
                    endLocationChoice.add("Tampa, FL");
                    endLocationChoice.add("Atlanta, GA");
                    endLocationChoice.add("Chicago, IL");
                    endLocationChoice.add("Boston, MA");
            partTwoPanel.add(vehicleSizeLabel);
                Choice vehicleSizeChoice = new Choice();
                vehicleSizeChoice.addItemListener(this);
                    vehicleSizeChoice.add("Compact");
                    vehicleSizeChoice.add("Mid-Size");
                    vehicleSizeChoice.add("Luxury");
                    vehicleSizeChoice.add("SUV");
            partTwoPanel.add(gasTypeLabel);
                Choice gasTypeChoice = new Choice();
                gasTypeChoice.addItemListener(this);
                    gasTypeChoice.add("Leaded");
                    gasTypeChoice.add("Unleaded");
                    gasTypeChoice.add("Super Unleaded");
                    gasTypeChoice.add("Diesel");
            partTwoPanel.add(submitButton);
                submitButton.addActionListener(this);
            partTwoPanel.add(clearButton);
                clearButton.addActionListener(this);

            //adds panels to the frame
            add(partOnePanel, BorderLayout.NORTH);
            add(partTwoPanel, BorderLayout.CENTER);
        }


        public void actionPerformed (ActionEvent e)
        {
        }

        public void itemStateChanged(ItemEvent ie)
        {
        }
}

Dani AI

Generated

Following 's move to Swing, the remaining task is wiring the four JComboBox components. Either an ItemListener or an ActionListener works; the practical difference is that ItemListener sends both DESELECTED and SELECTED ItemEvents (so check for SELECTED), while ActionListener fires when the selection is committed (often simpler if only the final selected value is needed). Attach the same listener to multiple combo boxes and distinguish them by source, or give each combo its own listener for clearer separation of logic.

A concise ItemListener pattern (handle only SELECTED) looks like:

vehicleBox.addItemListener(new ItemListener() {
    public void itemStateChanged(ItemEvent e) {
        if (e.getStateChange() == ItemEvent.SELECTED) {
            String sel = (String) e.getItem();
            // handle selection change for vehicleBox
        }
    }
});

A central ActionListener that handles buttons and combo boxes by source is also fine:

public void actionPerformed(ActionEvent e) {
    Object src = e.getSource();
    if (src == calcButton) {
        // calculate
    } else if (src == cityBox) {
        String selectedCity = (String) ((JComboBox) src).getSelectedItem();
        // handle city selection
    }
}

A few practical notes tied to 's current code: build the GUI on the Event Dispatch Thread via SwingUtilities.invokeLater; guard all parse calls with try/catch (NumberFormatException) or use JFormattedTextField/InputVerifier for numeric fields; prefer JComboBox<String> so casts are minimal; and keep UI-to-model logic separate (read selections, validate numeric input, then run calculations). These small changes eliminate common runtime errors and make the combo-box wiring straightforward.

Recommended Answers

All 3 Replies

Thanks I will try that

Here is my updated code. I know I need some kind of listener for my 4 JComboBox. What kind of listener do I need and how do I make it usable in my program?

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
{
    //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);
    }

    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);
                }
    }

}
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.