在JCombobox中有火车的可能路线。我想基于事件处理程序获取JCombobox的值,然后在使用数据库的类中使用它。此值将是Mysql查询的参数。我已成功获取它,但无法使用它。我对Java的经验不是很丰富,我做错了什么。我已经在该网站上搜索了类似的问题,发现了这些问题但不清楚地了解它们。我想念什么?

//imports...

public class Cashier extends JFrame{

      //here is main...
 public Cashier(){

      //some Window code...

     final  String[] Routes = {"--Select--", "value1",....."valueN" };
     final JComboBox comboBox = new JComboBox(Routes);

     comboBox.addActionListener(new ActionListener() {
       /*-->*/ public String d;
            public void WhereTo(String dest){

                 this.d=dest;
                   System.out.println(d);

          // comes out correct!
      /*I want d for use in DBaccess class as query parameter, by invoking
        GetRoute()*/
}

         public void actionPerformed(ActionEvent e) {
                 int val = comboBox.getSelectedIndex();
                         this.d= Routes[val];
              WhereTo(d);

        }
     });
            comboBox.setBounds(165, 124, 130, 23);
    contentPane.add(comboBox);

   //this method will be used by DBaccess

   public String GetRoute(){

     return d;
    }

    //More Objects...
  }
}


这是我的DBaccess类,可能要通过调用Cashier的Get Route()来使用字符串d。

 public DBaccess extends Cashier{

  //connection code....

 // Executing the query
  System.out.println("Creating statement...");
  stmt = conn.createStatement();
  String sql;

 //probably like this...
 String go = Cashier.GetRoute();

  sql = "SELECT FROM reservations WHERE destination='"+go+"'";
  ResultSet rs = stmt.executeQuery(sql);
  }

最佳答案

这里:

String go = Cashier.GetRoute();


此方法不是静态的,因此不能以这种方式调用。无论如何,这是一个糟糕的设计选择。考虑为DBaccess类提供所需路由的设置器。 actionPerformed()实现应如下所示:

@override
public void actionPerformed(ActionEvent e) {
    JComboBox comboBox = (JComboBox)e.getSource();
    String selectedRoute = (String)comboBox.getSelectedItem();
    DBaccess dbAccess = new DBaccess();
    dbAccess.setRoute(selectedRoute);
    dbAccess.setVisible(true);
}


一些提示可以帮助您:


Cashier extends JFrame:如果不添加一些与Swing相关的功能,请不要从swing组件扩展。您可以改用简单变量。
DBaccess extends Cashier(从JFrame扩展):一个典型的Swing应用程序应该只有一个JFrame。您应该改为使用JDialog。见The Use of Multiple JFrames, Good/Bad Practice?
DBaccess类提供一种方法,以从另一个类(Cashier)设置所需的路由。
您尝试执行的查询容易受到SQL Injection攻击。看看PreparedStatement可以避免这种情况。
如果DBaccess类将使用Swing组件显示查询结果,则您可能要看一下SwingWorker类在后台线程中进行数据库调用并更新Event Dispatch Thread中的Swing组件。请查看Concurrency in Swing跟踪以了解更多详细信息。

10-07 19:00
查看更多