我正在关注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));
AND
Cannot make a static reference to the non-static method PopulateJCB() from the type
执行
当我试图调用PopulateJCB()时发生;在主要方法
我知道教程视频中的代码并不完全相同,但我在这里尝试做类似的事情。请帮忙。
答案 0 :(得分:4)
范围!您在构造函数中声明了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