我正在遵循youtube教程(http://www.youtube.com/watch?v=wpbQ0DCFF0M)来用数据库表填充名为“ comboAccountName”的JCombobox。我的数据库连接是在另一个类中设置的。
代码如下-
public class Execute extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
//---------------------------------------------------------------------------------------------------------------------
public Execute()
{
.............other code...............
JComboBox comboAccountName = new JComboBox();
comboAccountName.setBounds(313, 31, 302, 20);
getContentPane().add(comboAccountName);
.............other code...............
}
void PopulateJCB()
{
String queryString = "SELECT DISTINCT [Account Name] FROM main ORDER BY [Account Name]";
try
{
Connection statJCBaccountname = DatabaseConnection.ConnectDB();
Statement stmt = statJCBaccountname.createStatement();
ResultSet rsJCBaccountname = stmt.executeQuery(queryString);
while (rsJCBaccountname.next())
{
comboAccountName.addItem(rsJCBaccountname.getString(1));
System.out.println(rsJCBaccountname.getString(1));
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Execute frame1 = new Execute();
frame1.setVisible(true);
PopulateJCB();
}
需要您帮助的2个错误
comboAccountName cannot be
解决
发生在while循环内的下一行
comboAccountName.addItem(rsJCBaccountname.getString(1));
和
Cannot make a static reference to the non-static method PopulateJCB() from the type
执行
当我尝试调用PopulateJCB()时发生;在主要方法中
我知道教程视频中的代码并不完全相同,但是我正在尝试做类似的事情。请帮忙。
范围!您在构造函数内部声明了comboAccountName,因此它仅在构造函数内部可见。尝试在其他地方使用它会失败。解决方案:在类级别的构造函数外部声明它。
所以不是:
public class Execute extends JFrame {
public Execute()
{
JComboBox comboAccountName = new JComboBox(); // this guy is visible only in here
comboAccountName.setBounds(313, 31, 302, 20); // don't do this!
getContentPane().add(comboAccountName);
}
反而:
public class Execute extends JFrame {
private JComboBox comboAccountName = new JComboBox();
public Execute()
{
comboAccountName.setBounds(313, 31, 302, 20);
getContentPane().add(comboAccountName);
}
接下来,我们将讨论您使用空布局setBounds(...)
和绝对定位的情况。虽然对于新手来说,这似乎是创建复杂GUI的最佳方法,但是您对Swing GUI的创建工作越多,您就会发现,这样做越会使您的GUI变得直截了当,将其画在一个非常狭窄的角落,很难扩展或增强。只是不要这样做。
至于这个错误:
无法从类型静态引用非静态方法PopulateJCB()
您必须创建该类的实例,然后在该实例上而不是在类本身上调用该方法。
所以不是:
public static void main(String[] args) {
// TODO Auto-generated method stub // please clean your code of this before posting here
Execute frame1 = new Execute();
frame1.setVisible(true);
PopulateJCB();
但:
public static void main(String[] args) {
Execute frame1 = new Execute();
frame1.setVisible(true);
frame1.PopulateJCB(); // call it on the Execute instance, frame1
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句