我正在尝试创建一个组合框,根据我的数据库填充内部项目。目前数据库包含5条记录,分别是test1,test2,test3,test4,test5。我制作了一个循环,用于填充每条记录。
private void selectschoolActionPerformed(java.awt.event.ActionEvent evt) {
ResultSet rs = null;
selectschool.setVisible(true);
try{
rs = DAO.getAllSchool();
ArrayList allSchoolName = new ArrayList();
int count = 0;
while(rs.next()){
allSchoolName.add(rs.getString("SchoolName"));
count++;
}
Object ob[] = new Object[count];
for (int i = 0; i < count; i++){
ob[i] = allSchoolName.get(i);
selectschool.addItem(ob[i]);
}
}catch (Exception e){
System.out.println("Exception: " + e);
}
CreateTimeTable ctt = new CreateTimeTable();
ctt.setVisible(true);
String sch = selectschool.getSelectedItem().toString();
ctt.jTextArea1.setText(sch);
我已经在for循环中进行了测试,它循环了适当的时间来填充数组,所有的记录都不会少。但是当我下拉组合框时,在GUI中,它是空的。但是,当我单击并按住鼠标时,将其拖到下面的空白字段,它将选择test1并仅测试1.我怎样才能显示其余的值?我测试了它,ob []保存了需要输入组合框的正确记录。我认为它可能是choosechool.addItem(),它不能正常工作。 非常感谢,谢谢。
(DAO.getAllSchool();只从sql中检索数据库记录)
答案 0 :(得分:0)
您需要创建JComboBox
并为其添加ActionListener
。不创建ActionPerformed,并在其中设置JComboBox
。
试试这样:
// fill with values from ResultSet rs (however you obtain it)
ArrayList<String> schools = new ArrayList<String>();
while(rs.next())
schools.add(rs.getString("SchoolName"));
// create the JComboBox
final JComboBox<String> selectSchool = new JComboBox<String>(schools.toArray(new String[]{}));
// add an actionlistener
selectSchool.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// do something with e.g. printing the selection
String school = (String) selectSchool.getSelectedItem();
System.out.println("You selected " + school);
}
});
编辑:或者在一个完整的,非常简单但有效的例子中:
package sto;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JComboBox;
import javax.swing.JFrame;
public class Main {
public static void main(String[] args) {
// create school list (in your example here would be the ResultSet)
ArrayList<String> schools = new ArrayList<String>();
schools.add("School 1");
schools.add("School 2");
schools.add("School 3");
schools.add("School 4");
// create the JComboBox
final JComboBox<String> selectSchool = new JComboBox<String>(schools.toArray(new String[]{}));
// add an actionlistener
selectSchool.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// do something with e.g. printing the selection
String school = (String) selectSchool.getSelectedItem();
System.out.println("You selected " + school);
}
});
// create a JFrame and add the JComboBox
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(selectSchool);
frame.pack();
frame.setVisible(true);
}
}