sat*_*nam 2 java database oop swing
我正在按照 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();
}
Run Code Online (Sandbox Code Playgroud)
有 2 个错误,我需要您的帮助
comboAccountName cannot be
Run Code Online (Sandbox Code Playgroud)
解决
发生在 while 循环内部的下一行
comboAccountName.addItem(rsJCBaccountname.getString(1));
Run Code Online (Sandbox Code Playgroud)
和
Cannot make a static reference to the non-static method PopulateJCB() from the type
Run Code Online (Sandbox Code Playgroud)
执行
当我尝试调用 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);
}
Run Code Online (Sandbox Code Playgroud)
反而:
public class Execute extends JFrame {
private JComboBox comboAccountName = new JComboBox();
public Execute()
{
comboAccountName.setBounds(313, 31, 302, 20);
getContentPane().add(comboAccountName);
}
Run Code Online (Sandbox Code Playgroud)
接下来我们将讨论空布局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();
Run Code Online (Sandbox Code Playgroud)
但:
public static void main(String[] args) {
Execute frame1 = new Execute();
frame1.setVisible(true);
frame1.PopulateJCB(); // call it on the Execute instance, frame1
Run Code Online (Sandbox Code Playgroud)