我使用下面的代码使用另一个jcombobox将值添加到jcombobox,我需要根据jcombobox1中选择的一个值将值添加到jcombobox2而不附加值,这样有人可以告诉我一种方法来重置或清除选择其他选项时的组合框值? 下面是我的编码,我是java和netbeans的新手,所以如果有人可以帮助我会感激不尽:)
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/database1", "root", "senura123");
Statement stat = (Statement) con.createStatement();
String val=jComboBox1.getSelectedItem().toString();
String check; String col;
if ("Vehicles".equals(val)){
check = "select reg_no from vehicle;";
col="reg_no";
}
else if ("Travel Guides".equals(val)){
check = "select username from travelguide;";
col="username";
}
else{
check = "select username from transportofficer";
col="username";
}
ResultSet rslt = stat.executeQuery(check);
while (rslt.next()) {
jComboBox2.addItem(rslt.getString(col));
}
}
答案 0 :(得分:9)
答案 1 :(得分:1)
将 new 模型设置到组合框中:
final List<String> values = new ArrayList<String>();
while (rslt.next()) {
values.add(rslt.getString(col));
}
jComboBox2.setModel(new DefaultComboBoxModel(values.toArray()));
作为进一步的评论,根据查询中涉及的延迟时间,您可能希望使用SwingWorker将此工作拆分为EDT和后台线程部分。
答案 2 :(得分:0)
通常会发生这种情况,因为您有一个与JComboBox相关联的事件。如果您在JComboBox中有控制项来执行操作,则会解决此问题,例如:
jComboBoxExample.addActionListener (new ActionListener () {
public void actionPerformed (ActionEvent e) {
do_run ();
}
});
public void do_run() {
int n=jComboBoxPerfilDocumentos.getItemCount(); <--THIS IS THE SOLUTION
if (n> 0) {
String x = jComboBoxPerfilDocumentos.getSelectedItem (). ToString ();
}
}