Search code examples
javaswingjdbcjcombobox

How to take String of a JComboBox Event handler into a variable for query?


In the JCombobox are possible Routes for a train.I want to get the value of JCombobox based on the event handler and then use it in a class that uses a Database. This value will be a parameter for a Mysql query.I have succeeded in getting it,but can not use it. I'm not very experienced in java, I am doing something wrong. I have searched the site for similar problems, seen them but not understood them clearly.What am I missing?

//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...
  }
}

This is my DBaccess class where i want to use the string d, probably by invoking Get Route() of Cashier.

 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);
  }

Solution

  • Here:

    String go = Cashier.GetRoute();
    

    This method is not static and it can't be invoked in this way. In any case it's a poor design choice. Consider providing DBaccess class with a setter for the desired route. The actionPerformed() implementation should look like this:

    @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);
    }
    

    Some tips to help you:

    • Cashier extends JFrame: don't extend from swing components if you won't add some Swing related functionality. You can use a simple variable instead.

    • DBaccess extends Cashier (which extends from JFrame): a tipical Swing application should have only one JFrame. You should use JDialog instead. See The Use of Multiple JFrames, Good/Bad Practice?

    • Provide DBaccess class with a method to set the desired route from another class (Cashier).

    • The query you're trying to execute is vulnerable to SQL Injection attacks. Take a look to PreparedStatement to avoid this.

    • If DBaccess class will display the query results using Swing components, then you may want to take a look to SwingWorker class to do the database call in a background thread and update Swing components in the Event Dispatch Thread. Take a look to Concurrency in Swing trail for more details.