简体   繁体   中英

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

accountNumber <> customerName <> balance

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

 //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

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. Your HashMap can handle that. 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).
  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.

Now, let's jump into the code. Let's assume that your accounts.txt file contains these following sample records:

JO123 <> John <> 12,000

SM456 <> Smith <> 15,000

Mi789 <> Mike <> 18,000

Ha121 <> Harvey <> 40,000

Lo321 <> Louis <> 38,000

Now, your AccountUtility class should be looking like this:

 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 .

And in order to set the customerName and balance to the text field, you need to define an ActionListener to the JComboBox .

So, you can write your accountApp() method like this:

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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