PSK
PSK

Reputation: 3

I can't select an entry in my ComboBox

So, i'm making a converter program for fun, and have run into an issue changing the entries in the JComboBoxes. I did get finally get it to change the contents, but couldn't select my unit to actually do my conversion.

private JComboBox comboBox;
private static JComboBox comboBox2;
private static JComboBox numberBox;
private static JComboBox typebox;

public Converter() {
    setTitle("ComboBoxTest");
    setSize(500,200);
    addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent e) {
            System.exit(0);
        }
    });
    String types[]={"Choose one", "Distance", "Weight"};
    typebox=new JComboBox(types);
    String choice=(String)typebox.getSelectedItem();
    String  measurementsw[]={"Choose one", "Pounds", "Kilograms", "Grams"};
    String measurementsd[]={"Choose one", "Meters", "Feet", "Inches", "Miles", "Yards"};
    String starts[]={"Choose one"};
    numberBox= new JComboBox();
    numberBox.setEditable(true);
    numberBox.addActionListener(this);
    typebox.addActionListener(this);
    JPanel t= new JPanel();
    t.add(typebox);
    t.add(numberBox);
    getContentPane().add(t, "North");
    DefaultComboBoxModel model = new DefaultComboBoxModel( measurementsd );
    DefaultComboBoxModel model2 = new DefaultComboBoxModel( measurementsd );
    comboBox = new JComboBox(model);
    comboBox2= new JComboBox(model2);
    comboBox.addActionListener(this);
    comboBox2.addActionListener(this);
    JPanel p = new JPanel();
    p.add(comboBox);
    JPanel q= new JPanel();
    q.add(comboBox2);
    getContentPane().add(p, "West");
    getContentPane().add(q, "East");
    getContentPane().add(result, "Center");
    ;
}
public void actionPerformed(ActionEvent evt) {
    //gets the word in each dropdown
    String type= (String) typebox.getSelectedItem();

    if (type.toLowerCase().equals("distance"))
    {
        //Changes contents of the dropdowns to distance measurements
        String measurementsd[]={"Choose one", "Meters", "Feet", "Inches", "Miles", "Yards"};
        DefaultComboBoxModel model = new DefaultComboBoxModel( measurementsd );
        DefaultComboBoxModel model2 = new DefaultComboBoxModel( measurementsd );
        comboBox.setModel(model);
        comboBox2.setModel(model2);
        String item = (String) comboBox.getSelectedItem();
        String item2 = (String) comboBox2.getSelectedItem();
        String item3 = (String) numberBox.getSelectedItem();
        //does the actual conversions
        if (item.toLowerCase().equals("choose one")||item2.toLowerCase().equals("choose one"))
        {  result.setText("Choose your Measurements");
        }
        if (item.toLowerCase().equals("meters"))
        {  result.setText(DConvert.ConverMeter(item3, item2));
        }
        if (item.toLowerCase().equals("yards"))
        {  result.setText(DConvert.ConverYard(item3, item2));
        }
        if (item.toLowerCase().equals("miles"))
        {  
            result.setText(DConvert.ConverMile(item3, item2));
        }
        if (item.toLowerCase().equals("inches"))
        {  result.setText(DConvert.ConverInch(item3, item2));
        }
        if (item.toLowerCase().equals("feet"))
        {  
            result.setText(DConvert.ConverFeet(item3, item2));
        }
    }   
    if (type.toLowerCase().equals("weight"))
    {
        //Changing contents of the dropdowns to the weight measurements
        changeToWeight();
        result.setText("Sorry, no can do!");
    }

}
public void changeToWeight(){
    String  measurementsw[]={"Choose one", "Pounds", "Kilograms", "Grams"};
    DefaultComboBoxModel model = new DefaultComboBoxModel( measurementsw );
    DefaultComboBoxModel model2 = new DefaultComboBoxModel( measurementsw );
    comboBox.setModel( model );
    comboBox2.setModel(model2);
}

public static void main(String[] args) {
    JFrame frame = new Converter();
    frame.show();
}

} when ran, it will change the contents, but i can't do the selection needed. Ignore DConvert, thats some seperate class i made

Upvotes: 0

Views: 1128

Answers (1)

Gilbert Le Blanc
Gilbert Le Blanc

Reputation: 51485

It took me 30 minutes to get your code to compile without any warnings.

  1. The first JComboBox fills out the other two JComboBoxes. So, we need an item listener to listen to the JComboBox, and fill the other two JComboBoxes.

  2. I used a JTextField for the input number as well as the output number.

  3. I used a JButton to trigger the calculation.

  4. I rearranged the Swing components to an order I thought made more sense.

  5. I broke up your monolithic code into several methods. That way, I could test each method separately.

  6. I started to create a List of conversion factors. You'll have to finish creating the List. By using a List, the JButton action listener is only 6 lines long for all conversions.

  7. Lastly, I made a call to the SwingUtilities invokeLater method in the main method to make sure that the Swing components were being created and used on the Event Dispatch thread.

So, here's the GUI.

ComboBox Test

And here's the code.

package com.ggl.testing;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.List;

import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class Converter extends JFrame {

    private static final long serialVersionUID = 7049836604855145085L;

    private DefaultComboBoxModel<String> inputModel;
    private DefaultComboBoxModel<String> outputModel;

    private JButton submitButton;

    private JComboBox<String> inputComboBox;
    private JComboBox<String> outputComboBox;
    private JComboBox<String> typeComboBox;

    private JTextField inputDimensionField;
    private JTextField outputDimensionField;

    private List<ConversionFactor> conversionFactors;

    public Converter() {
        this.conversionFactors = createConversionFactors();

        setTitle("ComboBoxTest");
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
        add(createConversionPanel(), BorderLayout.CENTER);
        add(createButtonPanel(), BorderLayout.SOUTH);
        pack();
    }

    private JPanel createConversionPanel() {
        JPanel panel = new JPanel();

        String types[] = { "Choose one", "Distance", "Weight" };
        typeComboBox = new JComboBox<String>(types);
        typeComboBox.setSelectedIndex(0);
        typeComboBox.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent event) {
                if (event.getStateChange() == ItemEvent.SELECTED) {
                    if (event.getItem().equals("Distance")) {
                        changeToDistance();
                    } else if (event.getItem().equals("Weight")) {
                        changeToWeight();
                    }
                }
            }
        });
        panel.add(typeComboBox);

        inputDimensionField = new JTextField(10);
        panel.add(inputDimensionField);

        String measurements[] = { "Choose one" };
        inputComboBox = new JComboBox<String>(measurements);
        panel.add(inputComboBox);

        JLabel label = new JLabel("converts to");
        panel.add(label);

        outputDimensionField = new JTextField(10);
        panel.add(outputDimensionField);

        outputComboBox = new JComboBox<String>(measurements);
        panel.add(outputComboBox);

        return panel;
    }

    private void changeToDistance() {
        String measurementsd[] = { "Choose one", "Meters", "Feet", "Inches",
                "Miles", "Yards" };
        inputModel = new DefaultComboBoxModel<String>(measurementsd);
        outputModel = new DefaultComboBoxModel<String>(measurementsd);
        inputComboBox.setModel(inputModel);
        outputComboBox.setModel(outputModel);
    }

    private void changeToWeight() {
        String measurementsw[] = { "Choose one", "Pounds", "Kilograms", "Grams" };
        inputModel = new DefaultComboBoxModel<String>(measurementsw);
        outputModel = new DefaultComboBoxModel<String>(measurementsw);
        inputComboBox.setModel(inputModel);
        outputComboBox.setModel(outputModel);
    }

    private JPanel createButtonPanel() {
        JPanel panel = new JPanel();

        submitButton = new JButton("Convert");
        submitButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent event) {
                double input = Double.parseDouble(inputDimensionField.getText());
                String inputValue = (String) inputComboBox.getSelectedItem();
                String outputValue = (String) outputComboBox.getSelectedItem();
                double output = input
                        * getConversionFactor(inputValue, outputValue);
                String s = String.format("%.2f", output);
                outputDimensionField.setText(s);
            }
        });
        panel.add(submitButton);

        return panel;
    }

    private double getConversionFactor(String inputValue, String outputValue) {
        for (ConversionFactor factor : conversionFactors) {
            if (inputValue.equalsIgnoreCase(factor.getInputUnit())
                    && outputValue.equalsIgnoreCase(factor.getOutputUnit())) {
                return factor.getConversionFactor();
            }
        }
        return 1.0D;
    }

    private List<ConversionFactor> createConversionFactors() {
        List<ConversionFactor> conversionFactors = new ArrayList<ConversionFactor>();
        ConversionFactor factor = new ConversionFactor("meters", "feet",
                3.2808D);
        conversionFactors.add(factor);
        factor = new ConversionFactor("meters", "inches", 39.370D);
        conversionFactors.add(factor);

        // I'll leave the rest for you to fill out.

        return conversionFactors;
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new Converter();
                frame.setVisible(true);
            }
        });
    }

    public class ConversionFactor {

        private final String inputUnit;
        private final String outputUnit;

        private final double conversionFactor;

        public ConversionFactor(String inputUnit, String outputUnit,
                double conversionFactor) {
            this.inputUnit = inputUnit;
            this.outputUnit = outputUnit;
            this.conversionFactor = conversionFactor;
        }

        public String getInputUnit() {
            return inputUnit;
        }

        public String getOutputUnit() {
            return outputUnit;
        }

        public double getConversionFactor() {
            return conversionFactor;
        }

    }

}

Upvotes: 1

Related Questions