从文件中读取并使用新数据填充现有的JComboBox

时间:2018-11-23 18:56:01

标签: java arrays swing file jcombobox

我正在尝试编写一个转换程序,在该程序中可以将新文件加载到程序中并更改转换(如果文件已损坏,还需要包括验证)。我目前已对转换进行了硬编码,并希望扩展程序,以便它接受来自外部txt文件的转换因子。

我是编程新手,真的不了解该如何做,有人可以帮忙吗?

public class CurrencyPanel extends JPanel{

//Declaring global variables which include buttons, labels, comboBox and a CheckBox
    private final static String[] conversionList = { "Euro (EUR)", "US Dollers(USD)", "Australian Dollars (AUD)", 
                                            "Canadian Dollars (CAD)", "Icelandic Króna (ISK)", "United Arab Emirates Dirham (AED)", 
                                            "South African Rand (ZAR)", "Thai Baht (THB)"};
    private JTextField inputField;
    private JLabel labelOutput, labelCount, labelReverse;
    private JCheckBox reverseCheck;
    private JComboBox<String> comboSelect;
    private int count = 0;


    public MainPanel mainPanel;

CurrencyPanel() {

    //initialising the convertListner to listener
            ActionListener listener = new ConvertListener();

            //setting comboBox to variable of list of conversions
            comboSelect = new JComboBox<String>(conversionList);
            comboSelect.setToolTipText("Select Conversion Type"); //ToolTip

            JLabel labelEnter = new JLabel("Enter value:"); //enter value label


            JButton convertButton = new JButton("Convert"); //convert button
            convertButton.addActionListener(listener); // convert values when pressed
            convertButton.setToolTipText("Press to convert value"); //ToolTip

            JButton clearButton = new JButton ("Clear"); //clear button
            clearButton.addActionListener(new ClearLabel()); //clear labels when button pressed
            clearButton.setToolTipText("Press to Clear Value & Conversion Counter"); //ToolTip

            labelOutput = new JLabel("---"); //label to be changed when conversion done
            inputField = new JTextField(5); //textField for the user to input
            inputField.addActionListener(listener); //Press return to do conversion
            labelOutput.setToolTipText("Conversion Value"); //ToolTip
            inputField.setToolTipText("Enter the value you wish to convert"); //ToolTip

            labelCount = new JLabel("Conversion Count: 0"); //Conversion count label to be changed when conversion occurs
            labelCount.setToolTipText("Amount of conversions made"); //ToolTip

            labelReverse = new JLabel("Reverse Conversion"); //ReverseConversion label
            reverseCheck = new JCheckBox(); //new CheckBox
            reverseCheck.setToolTipText("Check the box to reverse the conversion type"); //ToolTip

            //adding components to the panel
            add(comboSelect);
            add(labelEnter);
            add(inputField);
            add(convertButton);
            add(labelOutput);


            //setting size and colour of panel
            setPreferredSize(new Dimension(800, 100));
            setBackground(Color.cyan);

        }

            public void clearLabelMethod() {
                labelOutput.setText("---");
                inputField.setText("");
                count = 0;
                labelCount.setText("Conversion Count: 0");
            }




            //ActionListener to clear labels 
            private class ClearLabel implements ActionListener{
                @Override
                public void actionPerformed(ActionEvent e)
                {
                    labelOutput.setText("---");
                    inputField.setText("");
                    count = 0;
                    labelCount.setText("Conversion Count: 0");
                }
            }



        //ActionListener that does the main conversions
        private class ConvertListener implements ActionListener {


            @Override
            public void actionPerformed(ActionEvent event) {

                String text = inputField.getText().trim();

                //attempting to clear the combo box before repopulating
                comboSelect.removeAllItems();

                //try block to display message dialog
                try {   
                    Double.parseDouble(text); //checking to see if value is an double
                    if(inputField.getText().isEmpty()) 
                    { //if statement to check if inputField is empty


                    }
                }catch (Exception e) {
                    JOptionPane.showMessageDialog(null, "Please enter a valid number"); //message dialogue
                    return;
                }

                // if exception isn't thrown, then it is an integer
                if (text.isEmpty() == false) {

                    double value = Double.parseDouble(text); //converting double to string

                    // the factor applied during the conversion
                    double factor = 0;

                    // the offset applied during the conversion.
                    double offset = 0;

                    String symbol = null;


                    // Setup the correct factor/offset values depending on required conversion
                    switch (comboSelect.getSelectedIndex()) {

                    case 0: // Euro
                        factor = 1.359;
                        symbol = "€";
                        break;

                    case 1: // USD
                        factor = 1.34;
                        symbol = "$";
                        break;

                    case 2: // AUD
                        factor = 1.756;
                        symbol = "$";
                        break;

                    case 3: // CAD  
                        factor = 1.71;
                        symbol = "$";
                        break;

                    case 4: // ISK  
                        factor = 140.84;
                        symbol = "kr";
                        break;

                    case 5: // AED
                        factor = 4.92;
                        symbol = "د.إ";
                        break;

                    case 6: // ZAR  
                        factor = 17.84;
                        symbol = "R";
                        break;

                    case 7: // THB
                        factor = 43.58;
                        symbol = "฿";
                        break;
                    }


                    double result = 0;

                    if(mainPanel.reverseCheckMethod() == true) { //if the reverse check option is selected
                        result = value / factor - offset;   //do the opposite conversion

                    }else {
                        result = factor * value + offset; //if not then do regular conversion
                    }

                    DecimalFormat decFormat = new DecimalFormat("0.00"); //DecimalFormat of output
                    String formatted = decFormat.format(result); //formatting the result 2 decimal places

                    mainPanel.conCount();

                    labelOutput.setText(symbol+formatted); //setting the output label


                }
            }

        }

        public void loadFile() {

            int itemCount = comboSelect.getItemCount();
            for(int i=0;i<itemCount;i++) {
                comboSelect.removeAllItems();
            }

            try {
                BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("currency.txt"), "UTF8"));

                String line = null;

                while ((line = br.readLine()) != null) {
                     String[] values = line.split(",");

                     String currencyType = values[0];
                     String currencyValueTxt = values[1];
                     String currencySymbol = values[2];

                     Double conversionValue = Double.parseDouble(currencyValueTxt);

                     comboSelect.addItem(currencyType);

                     br.close();
                }

            }catch(Exception e) {
                JOptionPane.showMessageDialog(null, "File Error");
            }

        }
}

有问题的货币文件采用UTF-8编码,如下所示:

Euro (EUR), 1.41, €
US Dollars (USD), 1.24, $
Australian Dollars (AUD), 1.86, $
Bermudan Dollar (BMD), 1.35, $
Icelandic króna (ISK),  141.24, kr
United Arab Emirates Dirham (AED), 4.12, د.إ
South African Rand (ZAR), 16.84, R
Thai Baht (THB), 42.58, ฿

1 个答案:

答案 0 :(得分:0)

您想开始使用自定义对象来保存相关数据。

因此,您首先要创建一个具有3个属性的Currency对象:

  1. 名称
  2. 费率
  3. 符号

类似的东西:

public class Currency
{
    private String name;
    private double rate;
    private String symbol;

    public Currency (String name, double rate, String symbol)
    {
        this.name = name;
        this.rate = rate;
        this.symbol = symbol;
    }

    // add getter methods here

    @Override
    public String toString()
    {
        return name;
    }
}

然后,您需要添加getter方法,getName(),getRate()和getSymbol(),以便可以从对象访问数据。

现在,您可以使用以下代码将“硬编码”货币对象添加到组合框中:

//comboSelect = new JComboBox<String>(conversionList);
comboSelect = new JComboBox<Currency>();
comboSelect.addItem( new Currency("Euro (EUR)", 1.23, "€") );
comboSelect.addItem( new Currency("US Dollar (USD), 1.23, "$") );
...

组合框的默认渲染器将调用Currency对象的toString()方法,以使文本显示在组合框中。

现在,大大简化了ActionListener组合框代码:

Currency currency = (Currency)comboSelect.getSelectedItem();
factor = currency.getRate();
symbol = currency.getSymbol();

不需要switch语句。

在当前设计中,您在数组中具有名称硬编码,而在ActionListener中具有速率/符号硬编码。通过这种设计,您可以将所有数据集中在一个简单的对象中。

因此,首先获得使用硬编码的Currency对象的基本逻辑。

然后,当您准备创建动态货币对象时,循环代码将类似于:

while ((line = br.readLine()) != null) 
{
    String[] values = line.split(",");
    double rate = Double.parseDouble( values[1] );
    Currency currency = new Currency(values[0], rate, values[2]); 
    comboSelect.addItem( currency);

     //br.close(); you only close the file after reading all the lines of data
}

br.close();

注意:使用toString()方法将文本显示在组合框中确实不是一个好主意。相反,您应该使用自定义渲染器。获得上述建议后,您可以查看:Combo Box With Custom Renderer,以获取有关此主题的更多信息。