嘿。今天一直忙于调试。生病给这个简短的版本。
我制作了一个从数据库中获取名称的数组列表。然后我将arraylist的内容放入一个字符串数组中。现在我也想在 JList 中显示数组内容。
奇怪的是它更早地工作。我有两种方法。那些也只是一点点练习,确保我正确地添加到 Jlist 中。所以这是关键代码。
这是我的代码的布局。
变量构造方法
在我的变量中,我定义了这 3 个
String[] contactListNames = new String[5];
ArrayList<String> rowNames = new ArrayList<String>();
JList contactList = new JList(contactListNames);
很简单。
在我的构造函数中,我再次拥有它们。
contactListNames = new String[5];
contactList = new JList(contactListNames);
//i dont have the array list defined though.
printSqlDetails();
// the prinSqldetails was too make sure that the connectionw as alright. and its working fine.
fillContactList();
// this is the one thats causing me grief. its where all the work happens.
// fillContactListTest();
// this was the tester that makes sure its adding to the list alright.
这是 fillContactListTest() 的代码
public void fillContactListTest()
{
for(int i = 0;i<3;i++)
{
try
{
String contact;
System.out.println(" please fill the list at index "+ i);
Scanner in = new Scanner(System.in);
contact = in.next();
contactListNames[i] = contact;
in.nextLine();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
继承人应该太工作的主要的。
public void fillContactList()
{
int i =0;
createConnection();
ArrayList<String> rowNames = new ArrayList<String>();
try
{
Statement stmt = conn.createStatement();
ResultSet namesList = stmt.executeQuery("SELECT name FROM Users");
try
{
while (namesList.next())
{
rowNames.add(namesList.getString(1));
contactListNames =(String[])rowNames.toArray(new String[rowNames.size()]);
// this used to print out contents of array list
// System.out.println("" + rowNames);
while(i<contactListNames.length)
{
System.out.println(" " + contactListNames[i]);
i++;
}
}
}
catch(SQLException q)
{
q.printStackTrace();
}
conn.commit();
stmt.close();
conn.close();
}
catch(SQLException e)
{
e.printStackTrace();
}
}
我真的需要帮助。我束手无策。我只是不明白为什么第一种方法会添加到 JList 没问题。但第二个不会。
contactListNames 数组和数组列表都可以很好地打印并在其中包含名称。但我也必须将它们转移到错误的 jlist 中。请帮忙
ps 我知道这很长。但相信我它的简短版本。