如何使用接受字符串作为组合框名称的方法填充 JComboBox [英] How to populate JComboBox using a method that accepts string as combobox name

查看:37
本文介绍了如何使用接受字符串作为组合框名称的方法填充 JComboBox的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 GUI 中填充多个 JComboBox.所以我想使用一个接受每个 JComboBox 名称作为参数的方法.这可能吗?

I would like to populate multiple JComboBox in a GUI. So I would like to use a method that accepts each JComboBox name as an argument. Is this possible?

cmbCustomers.addItem("customer name");

在上面的代码中,我想用传递给 populate 方法的任何可能的字符串替换 cmbCustomers.

In the code above I would like to replace cmbCustomers with any possible string that is passed to the populate method.

我试图从 populate 方法传递一个字符串参数来动态替换 cmbCustomers 组合框名称,但这似乎是不可能的.

I have tried to pass a string argument from a populate method to replace the cmbCustomers comboboxname dynamically, but it really doesn't seem possible.

我正在制作一个用数据库中的数据填充 JTables 的 GUI.在特定的 JTable 中选择一行会用所选行的数据填充一组 JComboBoxes.从这里可以使用 JComboBoxes 更改数据并将其保存回数据库.由于有多个 JComboBoxes,我想避免重复太多代码.

I'm making a GUI that populates JTables with data from a database. Selecting a row in a particular JTable populates a set of JComboBoxes with the selected row's data. From here the data can be changed using the JComboBoxesand saved back to the database. Because of the multiple JComboBoxesI'd like to avoid duplicating so much code.

推荐答案

通常,Java 变量名仅在编译时可用.您不能在运行时使用字符串值作为变量名1.相反,您应该使用一般的面向对象原则来解决您的问题.在这种情况下,您可以编写一个接受 JComboBox 参数的方法:

Generally, Java variable names are only available at compile time. You cannot use a String value as a variable name at run time1. Instead, you should use general Object Oriented principles to solve your problem. In this case, you can write a method which accepts a JComboBox parameter:

private void populateComboBox(JComboBox comboBox) {
    comboBox.addItem("customer name");
    // ... do anything else you wish with the comboBox
}

现在您可以使用任何 JComboBox 调用此方法.请注意,传递给方法的参数名称无关紧要.它可以是你想要的任何东西.例如:

Now you can call this method with any JComboBox. Note that the name of the parameter passed to the method does not matter. It can be anything you want. For example:

JComboBox cmbCustomers = new JComboBox();
populateComboBox(cmbCustomers);

JComboBox cmbOtherCustomers= new JComboBox();
populateComboBox(cmbOtherCustomers);

我强烈建议您尽可能多地了解方法和引用变量.这些概念对 Java 编程至关重要,将帮助您理解我上面的建议,并帮助您在未来使用它们解决类似问题.

I strongly suggest that you learn as much as you can about methods and reference variables. These concepts are critical to Java programming and will help you understand my suggestion above as well as help you use them to solve similar problems in the future.

1 从技术上讲,您可以使用反射 API 来执行此操作.反射旨在用于代码工具中的代码内省,而不是用于标准的日常编程.你绝对不应该用它来解决这里问到的常见问题.

这篇关于如何使用接受字符串作为组合框名称的方法填充 JComboBox的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆