简体   繁体   English

如何在Java GUI中使用JComboBox中的选择填充文本字段

[英]how to populate text field with a selection from a JComboBox in java GUI

I am new to java GUI I'm having trouble filling text field using a JComboBox data from a text file text files has multiple rooms with the following format 我是Java GUI的新手,我无法使用文本文件中的JComboBox数据填充文本字段,文本文件具有多个格式如下的房间

accountNumber <> customerName <> balance accountNumber <> customerName <>余额

when an account number is selected from the combo for the right name and balance need to populate on the text field so far I have a class called AccountUtility which reads the data from the text file I am using an ArrayList to populate the combo box and a hashmap to map all names and balances so far I am only able to populate the combo box I'm having problems filling in the text file any help and suggestions are really appreciated 当从组合中选择一个正确的名称和余额的帐号时,到目前为止,我需要在文本字段中填充一个名为AccountUtility的类,该类从文本文件中读取数据,我正在使用ArrayList填充组合框,并且到目前为止,映射所有名称和余额的哈希图我只能填充组合框我在填写文本文件时遇到问题,任何帮助和建议都非常感谢

 //class that reads text file//////
 public class AccountUtility {
    ArrayList<String> test = new ArrayList<String>();
    HashMap<String, String> map = new HashMap<String, String>();
    String[] number;
    String columns[], accountNumber, customerName,balance;
    int size;


public AccountUtility(){


    BufferedReader in = null;
    try{    // assume products.txt already exists
    in = new BufferedReader(new FileReader("accounts.txt"));
    String line = in.readLine();
    while(line != null)  {
    columns = line.split("<>");
    accountNumber = columns[0];
    customerName = columns[1];
    balance = columns[2];

    test.add(accountNumber);
    map.put(customerName, balance);


                    line = in.readLine();
            }
            in.close();
    }
    catch(IOException ioe)
    {
            System.out.println(ioe);
    }
} 
 public ArrayList<String> getAccountNumbers( ){
     return test;
}
public HashMap<String, String> getMap(){
    return map;
}




//method on main class that populates JComboBox
    public AccountApp() {

        initComponents();
        setLocationRelativeTo(null);

        // Populate JComboBox
        AccountUtility gc = new AccountUtility();
        for( String one : gc.getAccountNumbers()){ 
        accountNumberComboBox.addItem(one);
        }
    }

This is what the GUI looks so far 到目前为止,这就是GUI的外观

enter image description here 在此处输入图片说明

You are on the right track. 您走在正确的轨道上。 Your code requires a little bit of remodeling. 您的代码需要一点重构。 Let's walk through the code changes to be made. 让我们逐步进行代码更改。

  1. There is no need for an extra ArrayList to to hold account numbers. 不需要额外的ArrayList来保存帐号。 Your HashMap can handle that. 您的HashMap可以处理。 Make account number as a key and the combination of customerName and balance as value(This only holds good if your app has unique account numbers). 帐号作为key ,并将customerNamebalance的组合作为值(仅当您的应用具有唯一帐号时,此方法才有效)。
  2. Avoid writing business logic inside your constructor. 避免在构造函数中编写业务逻辑 If anything goes wrong, your object will not be created and this leads to many other issues. 如果发生任何错误,将不会创建您的对象,这会导致许多其他问题。 Instead, create a method say, fetchAccountDetailsFromFile(String filePath) which will read the file and create the resultant HashMap of account details. 而是创建一个方法,例如fetchAccountDetailsFromFile(String filePath) ,该方法将读取文件并创建帐户详细信息的结果HashMap

Now, let's jump into the code. 现在,让我们进入代码。 Let's assume that your accounts.txt file contains these following sample records: 假设您的accounts.txt文件包含以下示例记录:

JO123 <> John <> 12,000 JO123 <>约翰<> 12,000

SM456 <> Smith <> 15,000 SM456 <>史密斯<> 15,000

Mi789 <> Mike <> 18,000 Mi789 <>迈克<> 18,000

Ha121 <> Harvey <> 40,000 Ha121 <>哈维<> 40,000

Lo321 <> Louis <> 38,000 Lo321 <>路易<> 38,000

Now, your AccountUtility class should be looking like this: 现在,您的AccountUtility类应如下所示:

 public class AccountUtility {

        private Map<String, String> fetchAccountDetailsFromFile(String filePath){
            //Create Map
            Map<String, String> accountDetails = new HashMap<>();

            try(BufferedReader fileReader = new BufferedReader(new FileReader(new File(filePath)))){
                String eachLine = "";
                while((eachLine = fileReader.readLine()) != null){
                    //Split at '<>'
                    String[] details = eachLine.split("<>");
                    //if each line does not have 3 fields, continue.
                    if(details.length < 3){
                        continue;
                    }

                    //get details of each field.
                    String accountNumber = details[0];
                    String customerName = details[1];
                    String balance = details[2];

                    /*
                     * Create name and balance combined String
                     * Ex: nameBalPair = Smith|15,000 
                     */
                    String nameBalPair = customerName + "|" + balance;

                    //add into Map
                    accountDetails.put(accountNumber, nameBalPair);
                }
            }catch(IOException e){
                e.printStackTrace();
            }

            //return Map
            return accountDetails;
        }
//Yet to add accountApp() method
    }

Now, you can call this fetchAccountDetailsFromFile(String filePath) method in your accountApp() method to get the generated HashMap . 现在,您可以在accountApp()方法中调用此fetchAccountDetailsFromFile(String filePath) accountApp()方法以获取生成的HashMap

And in order to set the customerName and balance to the text field, you need to define an ActionListener to the JComboBox . 为了将customerNamebalance设置为文本字段,您需要为JComboBox定义一个ActionListener

So, you can write your accountApp() method like this: 因此,您可以这样编写您的accountApp()方法:

public void accountAPP(){
        //Initialize all your JFrames, JPanels etc.

        //call the method to get generated Map.
        Map<String, String> accDetails = fetchAccountDetailsFromFile(ACCOUNT_FILE_PATH);

        //Combo Box
        JComboBox<String> accountNumbers = new JComboBox<>();

        //Text Field for customerName
        JTextField customerName = new JTextField(20);

        //Text Field for balance
        JTextField balance = new JTextField(20);

        /*
         * Iterate through your keySet from the accDetails map
         * and add each key (acct. numbers) to the Combo box.
         */



        for(String accountNumber : accDetails.keySet()){
            accountNumbers.addItem(accountNumber);
        }

       /*
        * Add action listener for the combo box which will set the
        * text fields on account number selection.
        * (This is Java 7 style of adding an ActionListener)
        */
        accountNumbers.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                String selectedAccountNo = (String)accountNumbers.getSelectedItem();
                String custNameAndBal = accDetails.get(selectedAccountNo);

                // split the value obtained at '|' to get name and balance.
                String[] nameBalDetails = custNameAndBal.split("\\|");
                customerName.setText(nameBalDetails[0]);
                balance.setText(nameBalDetails[1]);

            }
        });

        /*
         * Add your components to JFrame and follow with your other business logic
         */ 

    }

This should help you in setting customer name and balance on selection of account number. 这将帮助您设置客户名称,并在选择帐号时保持平衡。

If you are using Java 8, you can also write the actionListener as: 如果您使用的是Java 8,则还可以将actionListener编写为:

accountNumbers.addActionListener(l -> {

                String selectedAccountNo = (String)accountNumbers.getSelectedItem();
                String custNameAndBal = accDetails.get(selectedAccountNo);
                String[] nameBalDetails = custNameAndBal.split("\\|");
                customerName.setText(nameBalDetails[0]);
                balance.setText(nameBalDetails[1]);
        });

I hope this helps you in your learning. 希望这对您的学习有所帮助。

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

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