【问题标题】:how to populate text field with a selection from a JComboBox in java GUIjava - 如何使用Java GUI中的JComboBox中的选择填充文本字段
【发布时间】:2016-12-05 05:14:30
【问题描述】:

我是 java GUI 新手,我在填写文本字段时遇到问题 使用来自文本文件的 JComboBox 数据 文本文件有多个房间,格式如下

accountNumber customerName balance

当从组合中选择一个帐号时 正确的名称和余额需要填充在文本字段中 到目前为止,我有一个名为 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);
        }
    }

这就是 GUI 到目前为止的样子

enter image description here

【问题讨论】:

  • 如果我错了,请纠正我。您想在下拉菜单中选择帐号时填写客户名称和余额文本框吗?
  • 没错

标签: java swing


【解决方案1】:

你在正确的轨道上。您的代码需要一些改造。让我们来看看要进行的代码更改。

  1. 不需要额外的ArrayList来持有账户 数字。你的HashMap 可以处理。将帐号设为 keycustomerNamebalance 的组合为 价值(仅当您的应用具有唯一帐号时才适用)。
  2. 避免在构造函数中编写业务逻辑。如果 出现任何问题,您的对象将不会被创建,这会导致 到许多其他问题。相反,创建一个方法说, fetchAccountDetailsFromFile(String filePath) 将读取 文件并创建帐户详细信息的结果HashMap

现在,让我们进入代码。 假设您的 accounts.txt 文件包含以下示例记录:

JO123 约翰 12,000

SM456 史密斯 15,000

Mi789 迈克 18,000

Ha121 哈维 40,000

Lo321 路易斯 38,000

现在,您的 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
    }

现在,您可以在accountApp() 方法中调用此fetchAccountDetailsFromFile(String filePath) 方法来获取生成的HashMap

为了将customerNamebalance 设置为文本字段,您需要为JComboBox 定义一个ActionListener

因此,您可以像这样编写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
         */ 

    }

这应该有助于您在选择帐号时设置客户名称和余额。

如果您使用的是 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]);
        });

希望这对你的学习有所帮助。

【讨论】:

  • 在 accountAPP 下使用 Map accDetails = fetchAccountDetailsFromFile(ACCOUNT_FILE_PATH);有没有办法直接调用 account.txt 文件?而不是调用文件路径
  • 是的,ACCOUNT_FILE_PATH 只不过是一个代表accounts.txt 文件路径的String。函数调用也可以这样:Map&lt;String, String&gt; accDetails = fetchAccountDetailsFromFile("C:/docs/accounts.txt")
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-12-24
  • 2012-10-03
  • 2014-10-20
  • 2013-07-22
  • 1970-01-01
  • 2021-10-25
  • 1970-01-01
相关资源
最近更新 更多