Solved

Populating a JComboBox from a mdb database

Posted on 2007-04-11
6
1,189 Views
Last Modified: 2013-11-23
I'm trying to populate a combo box from a mdb database. I feel I'm really close, but I keep getting the error " non-static variable jComboBox1 cannot be referenced from a static context"  Here is my code.  It errors on the line "jComboBox1.setModel(model);".  I'm not that proficient in Java programming, so a low-level explanation would be appreciated :)
/*
 * frmDelete.java
 *
 * Created on March 28, 2007, 4:25 PM
 */

/**
 *
 * @author  ehrstein
 */
import java.sql.*;
import javax.swing.DefaultComboBoxModel;
public class frmDelete extends javax.swing.JFrame {
   
    /** Creates new form frmDelete */
    public frmDelete() {
        initComponents();
       
    }
   
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
    private void initComponents() {
        jLabel13 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        btnOK = new javax.swing.JButton();
        btnCancel = new javax.swing.JButton();
        jComboBox1 = new javax.swing.JComboBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        jLabel13.setFont(new java.awt.Font("Papyrus", 1, 24));
        jLabel13.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel13.setText("Delete Client");

        jLabel1.setText("Please select a client to delete:");

        btnOK.setText("OK");
        btnOK.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnOKActionPerformed(evt);
            }
        });

        btnCancel.setText("Cancel");
        btnCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jLabel13, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 268, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(layout.createSequentialGroup()
                        .addContainerGap()
                        .add(jLabel1))
                    .add(layout.createSequentialGroup()
                        .add(48, 48, 48)
                        .add(btnOK, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 76, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(26, 26, 26)
                        .add(btnCancel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 78, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .add(layout.createSequentialGroup()
                        .addContainerGap()
                        .add(jComboBox1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(145, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(jLabel13)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jLabel1)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jComboBox1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(145, 145, 145)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(btnCancel)
                    .add(btnOK))
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnOKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOKActionPerformed

    }//GEN-LAST:event_btnOKActionPerformed

    private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed
    this.setVisible(false);
    }//GEN-LAST:event_btnCancelActionPerformed
   
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new frmDelete().setVisible(true);
                try {//Start Try
             
//Database Path
String Db_Path = "C:\\sales.mdb";

//Create a connection
Connection conn = DriverManager.getConnection("jdbc:odbc:DRIVER=Microsoft Access Driver (*.mdb);Dbq=" + Db_Path);
//Made it this far? Connection Open!
System.out.println("Connection Open!");

//Create SQL statement container.
Statement st = conn.createStatement();

//Create SQL code/query that SQL statement container is going to run against database.
String str_SQL = "SELECT [ClientName] FROM Client";

//Create an empty ResultSet and fill it up with SQL code/query results.
ResultSet rs = st.executeQuery(str_SQL);

//Create an empty DefaultComboBoxModel. Similar to ArrayList...
DefaultComboBoxModel model = new DefaultComboBoxModel();

//While there are still records to be added...
while (rs.next()){ //Start While
   
//...continue to fill up DefaultComboBoxModel, converting each record found to String.
model.addElement(rs.getObject(1).toString());

}//End While

//Once there are no more records to be added,
//...add results populated into DefaultComboBoxModel to jComboBox1.
jComboBox1.setModel(model);

//Close ResultSet.
rs.close();
//Close Statement container.
st.close();
//Close Connection.
conn.close();

} //End Try

catch (SQLException ex) {ex.printStackTrace();}

// End Button
    }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancel;
    private javax.swing.JButton btnOK;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel13;
    // End of variables declaration//GEN-END:variables
   
}

0
Comment
Question by:kmart6700
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
6 Comments
 
LVL 65

Expert Comment

by:rockiroads
ID: 18892454
Not sure exactly but a tutorial can be found here - it may help u
http://java.sun.com/docs/books/tutorial/uiswing/components/combobox.html
0
 

Author Comment

by:kmart6700
ID: 18892632
I've actually already been to that web site and had no luck, but thanks for the quick response.  
0
 
LVL 65

Expert Comment

by:rockiroads
ID: 18892728
Sorry then. I take it this has also been posted on the Java section. Looks like expertise in Swing is required
0
 
LVL 1

Accepted Solution

by:
mon_pacey8 earned 500 total points
ID: 18918612
try doing this.  near the bottom of your code

//instead of
    private javax.swing.JComboBox jComboBox1;


//try changing into
    private static javax.swing.JComboBox jComboBox1;
0
 
LVL 1

Expert Comment

by:Computer101
ID: 21159998
Forced accept.

Computer101
EE Admin
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In this post we will learn how to make Android Gesture Tutorial and give different functionality whenever a user Touch or Scroll android screen.
Access custom database properties are useful for storing miscellaneous bits of information in a format that persists through database closing and reopening.  This article shows how to create and use them.
In Microsoft Access, learn how to use Dlookup and other domain aggregate functions and one method of specifying a string value within a string. Specify the first argument, which is the expression to be returned: Specify the second argument, which …
With Microsoft Access, learn how to start a database in different ways and produce different start-up actions allowing you to use a single database to perform multiple tasks. Specify a start-up form through options: Specify an Autoexec macro: Us…

726 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question