我正在分配我的组合框以处理Value或Car Name,所以我创建了这段代码,NullPointerException总是错误,我的代码是错误的吗?
public CarRent()
{
initComponents();
setLocationRelativeTo(null);
try
{
AddItem();
}
catch(Exception e)
{
e.printStackTrace();
}
}
public void Conn() throws Exception
{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(conn1,user,pass);
}
public void AddItem() throws Exception
{
String s = "Select Car_Name from Car_Tbl";
rs = st.executeQuery(s);
while(rs.next())
{
System.out.println(cboCars);
cboCars.addItem(rs.getString("Car_Name"));
}
}
运行: 显示java.lang.NullPointerException 在trypo.CarRent.AddItem(CarRent.java:77) 在trypo.CarRent。(CarRent.java:50) 在trypo.CarRent $ 4.run(CarRent.java:413) 在java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:312) at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:745) at java.awt.EventQueue.access $ 300(EventQueue.java:103) at java.awt.EventQueue $ 3.run(EventQueue.java:706) at java.awt.EventQueue $ 3.run(EventQueue.java:704) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain $ 1.doIntersectionPrivilege(ProtectionDomain.java:76) at java.awt.EventQueue.dispatchEvent(EventQueue.java:715) at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242) at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161) at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138) at java.awt.EventDispatchThread.run(EventDispatchThread.java:91) 建立成功(总时间:3秒)
答案 0 :(得分:0)
尝试
Resultset rs = st.executeQuery(s)
While(rs.next())
{
cboCars.addItem(rs.getString("Car_Name");
}
您的rs变量需要初始化为ResultSet。
我也不知道你的代码在尝试之上。 应该是声明
Statement st = null;
String s = "Select Car_Name from Car_Tbl";
填充数组cboCars后。
JComboBox carList = new JComboBox(cboCars);
.....
Statement stmt = null;
String q = "select Car_Name from Car_Tbl"
String[] cars ;
int i = 0;
try {
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while(rs.next()) {
cars[i] = rs.getString("Car_Name");
i++;
} catch (SQLException e) {
}finally{
if(stmt !=null) { stmt.close();}
}
}
// Now You have an array populated with cars . Create your combo box with the data
JComboBox carList = new JComboBox(cars);