JCombobox

I am triying to give my users a choice of which database they want to connect to. To do this I am using a combobox which they will select one of the databases, and it will connect to that database. For some reason it does not like one particular line of code. Can someone tell me why? I have tryied what little I know, but with no luck. Here is the code:


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
import java.sql.*;

public class InteractiveSQL extends JFrame
                            implements ActionListener
{

  public static void main(String[] args)
  {
   

    //Set the default values for the cammand line args
    String user  = "quest";
    String password  = "quest";
    String url  = (String)dbList.getSelectedItem();<<<<---------
    String driver  = "sun.jdbc.odbc.JdbcOdbcDriver";
   
   

    //Up to 4 arguments in the sequence database url, driver, user, password
    switch(args.length)
                 {
                   case 4:
                     password = args[3];
                     user = args[2];
                      driver=args[1];
                      url = args[0];    
                    break;
                   case 3:
                     user = args[2];
                     driver = args[1];
                     url = args[0];
                    break;
                   case 2:
                     driver = args[1];
                     url = args[0];
                    break;
                   case 1:
                     url = args[0];
                    break;
                 }
    InteractiveSQL theApp = new InteractiveSQL(driver, url, user, password);
  }

  public void actionPerformed(ActionEvent e)
  {
    Object source = e.getSource();
    if(source == command)
      executeSQL();

    else if(source == clearQueryItem)
      command.setText("");

     else if(source == exitItem)
     {
       dispose();
       System.exit(0);
     }
  }

  public void executeSQL()
  {
    String query = command.getText();
    if(query == null)
      return;
    try
    {
      model.setResultSet(statement.executeQuery(query));
      status.setText("ResultSet has " + model.getRowCount() + " rows");
    }
    catch (SQLException sqle)
    {
      status.setText(sqle.getMessage());
    }
  }

  public InteractiveSQL(String driver, String url, String user, String password)
  {
    super("InteractiveSQL");
    setBounds(0, 0, 400, 300);
    setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    addWindowListener(new WindowHandler());
   
    //the list of dbs
    String[] dbs = { "jdbc:odbc:osdconnection", "jdbc:odbc:shippingconnection", "jdbc:odbc:employee", "jdbc:odbc:CustomerServiceConnection" };

    //to initialize the combobox
    JComboBox dbList = new JComboBox(dbs);
    dbList.addActionListener(this);
    getContentPane().add(dbList, BorderLayout.WEST);

    //allow user to type in new db name
    dbList.setEditable(true);
   
    //Add the input for the SQL statement at the top
    command.setToolTipText("Key SQL command and press Enter");
    command.addActionListener(this);
    getContentPane().add(command, BorderLayout.NORTH);

    //Add the status reporting area at the bottom
    status.setLineWrap(true);
    status.setWrapStyleWord(true);
    getContentPane().add(status, BorderLayout.SOUTH);

    //Create the menubar from the menu items
    JMenu fileMenu = new JMenu("File");
    fileMenu.setMnemonic('F');
    clearQueryItem.addActionListener(this);
    exitItem.addActionListener(this);
    fileMenu.add(clearQueryItem);
    fileMenu.add(exitItem);
    menuBar.add(fileMenu);
    setJMenuBar(menuBar);

    //Establish a database connection and set up the table
    try
    {
      Class.forName(driver);
      connection = DriverManager.getConnection(url, user, password);
      statement = connection.createStatement();

      model = new ResultsModel();
      JTable table = new JTable(model);
      table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
      resultsPane = new JScrollPane(table);
      getContentPane().add(resultsPane, BorderLayout.CENTER);

    }
    catch(ClassNotFoundException cnfe)
    {
      System.err.println(cnfe);
    }
    catch(SQLException sqle)
    {
      System.err.println(sqle);
    }
    pack();
    setVisible(true);
  }
  class WindowHandler extends WindowAdapter

  {
    //Handler for window closing event
    public void WindowClosing(WindowEvent e)
    {
      dispose();
      System.exit(0);
    }
  }

  JTextField command = new JTextField();
  JTextArea status = new JTextArea(3,1);
  JScrollPane resultsPane;

  JMenuBar menuBar = new JMenuBar();
  JMenuItem clearQueryItem = new JMenuItem("clear query");
  JMenuItem exitItem = new JMenuItem("Exit");

  Connection connection;
  Statement statement;
  ResultsModel model;
}

The line with the arrow beside it is the trouble maker. I get "Undefined variable or class name: dbList".

Can someone help me out with this?

Thanks
berg
LVL 4
berg1375Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

mrquijaCommented:
you need to declare dbList before you do the getSelectedItem().

so in other words,  you need to do your

JComboBox dbList = new JComboBox(dbs)

before you do:

String url = (String)dbList.getSelectedItem();

When it compiles, it doesn't know what dbList is yet.
0
berg1375Author Commented:
Okay, I changed the code and it compiles, but will not connect to the selected database. It doesn't seem to be putting the selected item from the combobox into the url variable. Am I doing something wrong?

I ended up having to declare the Jcombobox twice, could that be the problem? Here is the updated code:


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
import java.sql.*;

public class InteractiveSQL extends JFrame
                            implements ActionListener
{

  public static void main(String[] args)
  {
    String[] dbs = { "jdbc:odbc:osdconnection", "jdbc:odbc:shippingconnection", "jdbc:odbc:employee", "jdbc:odbc:CustomerServiceConnection" };

    //to initialize the combobox
    JComboBox dbList = new JComboBox(dbs);

    //Set the default values for the cammand line args
    String user  = "quest";
    String password  = "quest";
    String url  = (String)dbList.getSelectedItem();
    String driver  = "sun.jdbc.odbc.JdbcOdbcDriver";
   
   

    //Up to 4 arguments in the sequence database url, driver, user, password
    switch(args.length)
                 {
                   case 4:
                     password = args[3];
                     user = args[2];
                      driver=args[1];
                      url = args[0];    
                    break;
                   case 3:
                     user = args[2];
                     driver = args[1];
                     url = args[0];
                    break;
                   case 2:
                     driver = args[1];
                     url = args[0];
                    break;
                   case 1:
                     url = args[0];
                    break;
                 }
    InteractiveSQL theApp = new InteractiveSQL(driver, url, user, password);
  }

  public void actionPerformed(ActionEvent e)
  {
    Object source = e.getSource();
    if(source == command)
      executeSQL();

    else if(source == clearQueryItem)
      command.setText("");

     else if(source == exitItem)
     {
       dispose();
       System.exit(0);
     }
  }

  public void executeSQL()
  {
    String query = command.getText();
    if(query == null)
      return;
    try
    {
      model.setResultSet(statement.executeQuery(query));
      status.setText("ResultSet has " + model.getRowCount() + " rows");
    }
    catch (SQLException sqle)
    {
      status.setText(sqle.getMessage());
    }
  }

  public InteractiveSQL(String driver, String url, String user, String password)
  {
    super("InteractiveSQL");
    setBounds(0, 0, 400, 300);
    setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    addWindowListener(new WindowHandler());
   
    //the list of dbs
    String[] dbs = { "jdbc:odbc:osdconnection", "jdbc:odbc:shippingconnection", "jdbc:odbc:employee", "jdbc:odbc:CustomerServiceConnection" };

    //to initialize the combobox
    JComboBox dbList = new JComboBox(dbs);
    dbList.addActionListener(this);
    getContentPane().add(dbList, BorderLayout.WEST);

    //allow user to type in new db name
    dbList.setEditable(true);
   
    //Add the input for the SQL statement at the top
    command.setToolTipText("Key SQL command and press Enter");
    command.addActionListener(this);
    getContentPane().add(command, BorderLayout.NORTH);

    //Add the status reporting area at the bottom
    status.setLineWrap(true);
    status.setWrapStyleWord(true);
    getContentPane().add(status, BorderLayout.SOUTH);

    //Create the menubar from the menu items
    JMenu fileMenu = new JMenu("File");
    fileMenu.setMnemonic('F');
    clearQueryItem.addActionListener(this);
    exitItem.addActionListener(this);
    fileMenu.add(clearQueryItem);
    fileMenu.add(exitItem);
    menuBar.add(fileMenu);
    setJMenuBar(menuBar);

    //Establish a database connection and set up the table
    try
    {
      Class.forName(driver);
      connection = DriverManager.getConnection(url, user, password);
      statement = connection.createStatement();

      model = new ResultsModel();
      JTable table = new JTable(model);
      table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
      resultsPane = new JScrollPane(table);
      getContentPane().add(resultsPane, BorderLayout.CENTER);

    }
    catch(ClassNotFoundException cnfe)
    {
      System.err.println(cnfe);
    }
    catch(SQLException sqle)
    {
      System.err.println(sqle);
    }
    pack();
    setVisible(true);
  }
  class WindowHandler extends WindowAdapter

  {
    //Handler for window closing event
    public void WindowClosing(WindowEvent e)
    {
      dispose();
      System.exit(0);
    }
  }

  JTextField command = new JTextField();
  JTextArea status = new JTextArea(3,1);
  JScrollPane resultsPane;

  JMenuBar menuBar = new JMenuBar();
  JMenuItem clearQueryItem = new JMenuItem("clear query");
  JMenuItem exitItem = new JMenuItem("Exit");

  Connection connection;
  Statement statement;
  ResultsModel model;
}

Thanks
berg
0
berg1375Author Commented:
I am only rejecting this answer so I can get more opinions on this situation. You will receive your points, but I would also like to get this new problem fixed, because it goes along the same lines as the original problem.

Thanks
berg
0
Cloud Class® Course: Microsoft Exchange Server

The MCTS: Microsoft Exchange Server 2010 certification validates your skills in supporting the maintenance and administration of the Exchange servers in an enterprise environment. Learn everything you need to know with this course.

mrquijaCommented:
Well, when you first initialize your comboBox, I dont think anything is "automatically" selected. so with your first

String url  = (String)dbList.getSelectedItem();


, the url will be null or empty because nothing has been selected.

You need to put that statement (String url = ..) somewhere else in the code so that you are sure that the comboBox has been clicked on already.  If the user doesn't touch the comboBox because it's already on the database that he wants to connect to, then do a  ".getSelectedIndex(0);" instead.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
vivexpCommented:
Hi,

Ask said by mrquija , u r creating an object of jcombox in the constrctor, where it will become private variable.
Since u want to access dbList in the main()
Hence declare JComboBox dbList outside main() as
public static JComboBox dbList;

Instantiate the object in the constructor as
     dbList=new dbList();
This will compile without errors. The  dbList object can be accessed in the main() also..

Try out...........


Bye



0
vivexpCommented:
Hi,

Simple example to show what i meant...
import javax.swing.*;

public class MyClass1 {
public static JFrame f;

  public MyClass1() {

  }

  public static void main(String[] args) {
    MyClass1 myClass1 = new MyClass1();
     f=new JFrame();
    f.show (true);
    f.setBounds (0,0,100,100);
    f.pack ();
    myClass1.invokedStandalone = true;
  }
  private boolean invokedStandalone = false;
}
0
berg1375Author Commented:
vivexp-

With doing your code, will I still need the code for the combobox in the constructor? All I will need to do is reference it later?

I am new to Java, so forgive my ignorance.

Thanks
berg
0
berg1375Author Commented:
vivexp-

I put your code into the program, but it came back with two variable errors when I tried to compile it.

It said variable "f", and main can not be static. Here is the updated code:


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
import java.sql.*;

public class InteractiveSQL extends JFrame
                            implements ActionListener
{

  public class MyClass1
  {
    public static JFrame f;
   
      public MyClass1()
      {
      }

   public static void main(String[] args)
   {
   
    MyClass1 myClass1 = new MyClass1();
      f=new JFrame();
    f.show (true);
    f.setBounds (0,0,100,100);
    f.pack ();
    myClass1.invokeStandalone = true;

    //the list of dbs
    String[] dbs = { "jdbc:odbc:osdconnection", "jdbc:odbc:shippingconnection", "jdbc:odbc:Employee", "jdbc:odbc:CustomerService" };

    //to initialize the combobox
    JComboBox dbList = new JComboBox(dbs);
   
    //Set the default values for the cammand line args
    String user  = "quest";
    String password  = "quest";
    String url  = (String)dbList.getSelectedItem();
    String driver  = "sun.jdbc.odbc.JdbcOdbcDriver";
   
   

    //Up to 4 arguments in the sequence database url, driver, user, password
    switch(args.length)
                 {
                   case 4:
                     password = args[3];
                     user = args[2];
                      driver=args[1];
                      url = args[0];    
                    break;
                   case 3:
                     user = args[2];
                     driver = args[1];
                     url = args[0];
                    break;
                   case 2:
                     driver = args[1];
                     url = args[0];
                    break;
                   case 1:
                     url = args[0];
                    break;
                 }
    InteractiveSQL theApp = new InteractiveSQL(driver, url, user, password);
   }
  private boleen invokedStandalone = false;
  }
  public void actionPerformed(ActionEvent e)
  {
    Object source = e.getSource();
    if(source == command)
      executeSQL();

    else if(source == clearQueryItem)
      command.setText("");

     else if(source == exitItem)
     {
       dispose();
       System.exit(0);
     }
  }

  public void executeSQL()
  {
    String query = command.getText();
    if(query == null)
      return;
    try
    {
      model.setResultSet(statement.executeQuery(query));
      status.setText("ResultSet has " + model.getRowCount() + " rows");
    }
    catch (SQLException sqle)
    {
      status.setText(sqle.getMessage());
    }
  }

  public InteractiveSQL(String driver, String url, String user, String password)
  {
    super("InteractiveSQL");
    setBounds(0, 0, 400, 300);
    setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    addWindowListener(new WindowHandler());
   
    //the list of dbs
    String[] dbs = { "jdbc:odbc:osdconnection", "jdbc:odbc:shippingconnection", "jdbc:odbc:employee", "jdbc:odbc:CustomerServiceConnection" };

    //to initialize the combobox
    //JComboBox dbList = new JComboBox(dbs);
    //dbList.addActionListener(this);
    //getContentPane().add(dbList, BorderLayout.WEST);

    //allow user to type in new db name
    //dbList.setEditable(true);
   
    //Add the input for the SQL statement at the top
    command.setToolTipText("Key SQL command and press Enter");
    command.addActionListener(this);
    getContentPane().add(command, BorderLayout.NORTH);

    //Add the status reporting area at the bottom
    status.setLineWrap(true);
    status.setWrapStyleWord(true);
    getContentPane().add(status, BorderLayout.SOUTH);

    //Create the menubar from the menu items
    JMenu fileMenu = new JMenu("File");
    fileMenu.setMnemonic('F');
    clearQueryItem.addActionListener(this);
    exitItem.addActionListener(this);
    fileMenu.add(clearQueryItem);
    fileMenu.add(exitItem);
    menuBar.add(fileMenu);
    setJMenuBar(menuBar);

    //Establish a database connection and set up the table
    try
    {      
      Class.forName(driver);
      connection = DriverManager.getConnection(url, user, password);
      statement = connection.createStatement();

      model = new ResultsModel();
      JTable table = new JTable(model);
      table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
      resultsPane = new JScrollPane(table);
      getContentPane().add(resultsPane, BorderLayout.CENTER);

    }
    catch(ClassNotFoundException cnfe)
    {
      System.err.println(cnfe);
    }
    catch(SQLException sqle)
    {
      System.err.println(sqle);
    }
    pack();
    setVisible(true);
  }
  class WindowHandler extends WindowAdapter

  {
    //Handler for window closing event
    public void WindowClosing(WindowEvent e)
    {
      dispose();
      System.exit(0);
    }
  }

  JTextField command = new JTextField();
  JTextArea status = new JTextArea(3,1);
  JScrollPane resultsPane;

  JMenuBar menuBar = new JMenuBar();
  JMenuItem clearQueryItem = new JMenuItem("clear query");
  JMenuItem exitItem = new JMenuItem("Exit");

  Connection connection;
  Statement statement;
  ResultsModel model;
}


I have limited knowledge of java, so I don't know exactly what I can do to get around this. If you could help it would be greatly appreciated, and I will post another Q for your points. Thanks

berg
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.