简体   繁体   English

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

[英]Read from a file and populate existing JComboBox with new data

I am attempting to write a conversion program in which a new file can be loaded in to the program and change the conversion (needs to also include validation if the file is corrupted). 我正在尝试编写一个转换程序,在该程序中可以将新文件加载到程序中并更改转换(如果文件损坏,还需要包括验证)。 I currently have the conversions hard coded in and want to extend the program so that it accepts the conversion factors from an external txt file. 我目前已对转换进行了硬编码,并希望扩展程序,以便它接受来自外部txt文件的转换因子。

I am new to programming and don't really understand how to do this can someone help? 我是编程新手,并不真正了解如何做到这一点,有人可以帮忙吗?

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

        }
}

The currency file in question is encoded in UTF-8 and is as follows: 有问题的货币文件采用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, ฿

Well you want to start to use a custom object to hold related data. 好了,您想开始使用自定义对象来保存相关数据。

So you would start by creating a Currency object with 3 properties: 因此,您将从创建具有3个属性的Currency对象开始:

  1. Name 名称
  2. Rate
  3. Symbol 符号

Something like: 就像是:

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

You would then need to add getter methods, getName(), getRate() and getSymbol() so you can access the data from the object. 然后,您需要添加getter方法,getName(),getRate()和getSymbol(),以便可以从对象访问数据。

Now you can add the "hard coded" currency objects to your combo box with code like: 现在,您可以使用以下代码将“硬编码”货币对象添加到组合框中:

//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, "$") );
...

The default renderer for the combo box will invoke the toString() method of your Currency object for the text to display in the combo box. 组合框的默认渲染器将调用Currency对象的toString()方法,以使文本显示在组合框中。

Now the ActionListener code for you combo box is greatly simplified: 现在,大大简化了组合框的ActionListener代码:

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

No need for the switch statement. 不需要switch语句。

In your current design you have the names hard code in an Array and the rate/symbol hard coded in the ActionListener. 在当前设计中,您在Array中具有名称硬编码,而在ActionListener中具有比率/符号硬编码。 With this design you have all the data together in a simple object. 通过这种设计,您可以将所有数据集中在一个简单的对象中。

So first get this basic logic working with hard coded Currency objects. 因此,首先获得与硬编码的Currency对象一起使用的基本逻辑。

Then when you are ready to create dynamic currency objects your looping code would be something like: 然后,当您准备创建动态货币对象时,循环代码将类似于:

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

Note: it really isn't a good idea to use the toString() method for the text to display in the combo box. 注意:使用toString()方法在组合框中显示文本确实不是一个好主意。 Instead you should be using a custom renderer. 相反,您应该使用自定义渲染器。 Once you have gotten the above suggestions working you can check out: Combo Box With Custom Renderer for more information on this topic. 获得上述建议后,您可以签出: 具有自定义渲染器的组合框,以获取有关此主题的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM