Populating a JComboBox from a mdb database

Posted on 2007-04-11
Last Modified: 2008-02-01
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 :)
 * 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() {
    /** 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();

        jLabel13.setFont(new java.awt.Font("Papyrus", 1, 24));
        jLabel13.setText("Delete Client");

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

        btnOK.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {

        btnCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
                    .add(jLabel13, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 268, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .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(jComboBox1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(145, Short.MAX_VALUE))
                .add(jComboBox1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(145, 145, 145)
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    }// </editor-fold>//GEN-END:initComponents

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


    private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST: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 ({ //Start While
//...continue to fill up DefaultComboBoxModel, converting each record found to String.

}//End While

//Once there are no more records to be added,
//...add results populated into DefaultComboBoxModel to jComboBox1.

//Close ResultSet.
//Close Statement container.
//Close Connection.

} //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
Question by:kmart6700

Accepted Solution

EFelson earned 500 total points
ID: 18905475
I understand the lack of Java experience may be the issue here, so let me try to explain in simplest terms...
When your "main" runs, you "new" a frmDelete() which in turn creates a jComboBox1 <I>unique to that specific frmDelete instance</I>.  When you later reference jComboBox1, there is no way for the compiler to be certain to what JComboBox you are referring.  For example, let's assume you had "new'd" two (or three or five or a dozen) different frmDelete() objects before reaching the line that is giving you a compile error.  Which of those different objects would you expect jComboBox1 to be referring to?  What you probably want to do is to access that jComboBox1 in the context of a frmDelete object instance.  e.g. ..

frmDelete   fdlt = new frmDelete();

Of course the code above is not literally correct, as you would need to either make the jComboBox1 public and/or provide some sort of accessor method, etc but hopefully that explains the general idea...

Featured Post

Courses: Start Training Online With Pros, Today

Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Spring Framework HTTPSession management 1 33
javap bin 2 34
hibernate insert example 13 28
Why my table column Id is not passed to java object? 4 38
Whether you've completed a degree in computer sciences or you're a self-taught programmer, writing your first lines of code in the real world is always a challenge. Here are some of the most common pitfalls for new programmers.
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.

776 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