简体   繁体   English

如何用mySQL数据库中的信息填充jcombobox?

[英]How do I populate a jcombobox with information from a mySQL database?

Basically the program takes customer information and dumps it in a database. 基本上,该程序获取客户信息并将其转储到数据库中。 In order to change information I want the user to be able to pick a customer name from a combobox, so the system can then call all the info out of the database on that customer. 为了更改信息,我希望用户能够从组合框中选择一个客户名称,以便系统随后可以从该客户的数据库中调用所有信息。 Accessing the database is fine, putting info in and changing it is fine.. I just cant figure out how to get the combobox to populate with all the customer names. 访问数据库很好,可以放入信息并进行更改。.我只是想不出如何使组合框填充所有客户名称。

The simplest solution is to create an array of String from the database. 最简单的解决方案是从数据库创建String数组。 Then use that to create the combobox. 然后使用它来创建组合框。

  String[] mydbStrings = .....;
  JComboBox mycombo = new JComboBox(mydbStrings);

But that will give you only some strings. 但这只会给您一些字符串。 It may be better to define a class that represents the customer, load the customers from the database, ensure that an adequate toString() is defined in the Customer class and create an array of Customers that is used in the Combo Box. 最好定义一个代表客户的类,从数据库中加载客户,确保在Customer类中定义了足够的toString()并创建在组合框中使用的客户数组。 That way, the customer names are displayed in the combobox but hwen you select one you have all the customer details readily available. 这样,客户名称显示在组合框中,但是如果您选择一个,则可以轻松获得所有客户详细信息。

If you think this is too memory intensive to load all your customer's data at once it is possible to create a smaller custInfo class with just the name and ID. 如果您认为这占用大量内存,无法一次加载所有客户数据,则可以仅使用名称和ID创建较小的custInfo类。 Then use that in the combobox and load the rest of the customer data after it is selected. 然后在组合框中使用该数据集,并在选定数据后加载其余的客户数据。

This should be simple if you know how to populate a normal combobox, and how to pull the data from the database. 如果您知道如何填充普通的组合框,以及如何从数据库中提取数据,这应该很简单。 The combobox by default will take an array of strings in the constructor, so you could just pass an array of string(Customer names), but I would recommend creating a model for the combobox. 默认情况下,组合框将在构造函数中采用字符串数组,因此您可以仅传递字符串数组(客户名称),但是我建议为组合框创建一个模型。 You could then pass the Customers to the model(most likely some POJO's), and then you will also probably want to create a renderer so that you can display the names as you like. 然后,您可以将客户(最可能是一些POJO)传递给模型,然后您可能还想创建一个渲染器,以便可以根据需要显示名称。 Then when a customer is selected you can query the model to get an id for the selected customer, and then use that to retrieve the needed customer data. 然后,当选择了客户时,您可以查询模型以获取所选客户的ID,然后使用该ID检索所需的客户数据。

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

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