我无法在我的ComboBox中选择一个条目

时间:2015-03-24 17:45:04

标签: java

所以,我正在制作转换器程序以获得乐趣,并且遇到了更改JComboBox中条目的问题。我确实最终得到了更改内容,但无法选择我的单位来实际进行转换。

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

} 运行时,它会改变内容,但我不能进行所需的选择。忽略DConvert,这是我制作的一些单独的课程

1 个答案:

答案 0 :(得分:0)

我花了30分钟让你的代码编译而没有任何警告。

  1. 第一个JComboBox填写了另外两个JComboBox。所以,我们需要一个项目监听器来监听JComboBox,并填充其他两个JComboBox。

  2. 我使用JTextField作为输入数字和输出数字。

  3. 我使用JButton来触发计算。

  4. 我将Swing组件重新排列为我认为更有意义的订单。

  5. 我将您的单片代码分解为几种方法。这样,我可以单独测试每种方法。

  6. 我开始创建转换因子列表。您必须完成创建列表。通过使用List,JButton动作侦听器对于所有转换只有6行。

  7. 最后,我在main方法中调用了SwingUtilities invokeLater方法,以确保在Event Dispatch线程上创建和使用Swing组件。

  8. 所以,这是GUI。

    ComboBox Test

    这是代码。

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