I have 2 JComboBoxes that are using an itemListener, right now the code I have compiles but when I call for tankSize and fuelCost to complete my calculations nothing is returned and my answer is always zero. What do I need to change so the variables transfer to tankSize and fuelCost? Thanks for any help you can offer.

Here is the part of the code I'm trying to get to work:

        JComboBox vehicleBox= (JComboBox)ie.getSource();
            String tank = (String)ie.getItem();
            if(tank == "Compact")
            {
                tankSize = compactTank;
            }
            else if(tank == "Mid-Size")
            {
                tankSize = midSizeTank;
            }
            else if(tank == "Luxury")
            {
                tankSize = luxuryTank;
            }
            else if(tank == "SUV")
            {
                tankSize = suvTank;
            }


        JComboBox fuelBox = (JComboBox)ie.getSource();
            String fuelType = (String)ie.getItem();
            if(fuelType == "Leaded")
            {
                fuelCost = leadedCost;
            }
            else if(fuelType == "Unleaded")
            {
                fuelCost = unleadedCost;
            }
            else if(fuelType == "Super Unleaded")
            {
                fuelCost = superUnleadedCost;
            }
            else if(fuelType == "Diesel")
            {
                fuelCost = dieselCost;
            }

You'll need to elaborate on what ie is. I'm going to assume this is inside of an event listener of some sort. If that is the case, you shouldn't be casting both JComboBox objects to the source of the event.

Yes this code is inside Item Listener and the ie is from "public void itemStateChanged(ItemEvent ie)" I have 4 combo boxes in this method and the two of them that only need to return the word selected work the 2 i posted on here compile but do not return any variables so I cannot complete my calculations.

  • don't to recreate a new JComboBoxes instance inside ItemListener, then you lost referrence to the original JComboBox (fired event), create JComboBox only once time,

  • add ItemListener to both separatelly only to test SELECTED inside public void itemStateChanged(ItemEvent ie)

  • create ItemListaner class, there you determine which one firing an event, then to test for selected Item

  • for example (to 1st point)

code

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

public class ComboBoxListeners {

    private JFrame f;
    private JComboBox flyFromCombo;
    private JComboBox flyToCombo;
    private JLabel tripLabel = new JLabel();
    private Object[] itemsFrom;
    private Object[] itemsTo;

    public ComboBoxListeners() {
        itemsFrom = new Object[]{"-", "First - From", "Second - From", "Third - From"};
        itemsTo = new Object[]{"-", "First - To", "Second - To", "Third - To"};
        //flyFromCombo.setPrototypeDisplayValue("################################################");
        flyFromCombo = new JComboBox(itemsFrom);
        flyFromCombo.addItemListener(new ItemListener() {

            @Override
            public void itemStateChanged(ItemEvent e) {
                if ((e.getStateChange() == ItemEvent.SELECTED)) {
                    String str = flyFromCombo.getSelectedItem().toString();
                    String str1 = flyToCombo.getSelectedItem().toString();
                    setLabelText(str, str1);
                }
            }
        });
        flyToCombo = new JComboBox(itemsTo);
        flyToCombo.addItemListener(new ItemListener() {

            @Override
            public void itemStateChanged(ItemEvent e) {
                if ((e.getStateChange() == ItemEvent.SELECTED)) {
                    String str = flyFromCombo.getSelectedItem().toString();
                    String str1 = flyToCombo.getSelectedItem().toString();
                    setLabelText(str, str1);
                }
            }
        });
        tripLabel.setPreferredSize(new Dimension(400, 30));
        f = new JFrame("ComboBox ItemListeners");
        f.setLayout(new GridLayout(0, 1, 15, 15));
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(flyFromCombo);
        f.add(flyToCombo);
        f.add(tripLabel);
        f.setLocation(150, 150);
        f.pack();
        f.setVisible(true);
    }

    private void setLabelText(String str1, String str2) {
        String textForLabel = "";
        String helpStringFirst = str1.trim();
        if (helpStringFirst != null && helpStringFirst.length() > 0) {
            if (!helpStringFirst.equals("-")) {
                textForLabel = "Flight No57. from :   " + helpStringFirst;
            } else {
                textForLabel = "Flight from Un-Know :   ";
            }
        }
        String helpStringSecond = str2.trim();
        if (helpStringSecond != null && helpStringSecond.length() > 0) {
            if (!helpStringSecond.equals("-")) {
                textForLabel = textForLabel + "   --> to :   " + helpStringSecond;
            } else {
                textForLabel += "   to :   Un-Know    ";
            }
        }
        final String pushTextForLabel = textForLabel;
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                tripLabel.setText(pushTextForLabel);
            }
        });
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                ComboBoxListeners comboBoxListeners = new ComboBoxListeners();
            }
        });
    }
}

Edited 3 Years Ago by mKorbel

mKorbel:

Will you please explain why you have override run() in main() method with runnable()?
Actually i don't get it.

or can we use following code to get item from combo box on click or on selecting?

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

Thanks.

That works so far but I have variable set up so when an item from a JComboBox is picked, I want that item to equal its variable so the code that figures out how much a trip will cost, works. Right now all I get is the cost is $0 so I'm guessing the variable isn't transfering to my equation.

This question has already been answered. Start a new discussion instead.