用数据库信息填充jcombobox

时间:2009-10-27 00:34:01

标签: java mysql jcombobox

我知道我错过了一些简单的东西,我认为让组合框访问数组。

package my.freelancebillingapp;
import java.sql.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.ArrayList;
import javax.swing.*;

public class billingInfoUI extends javax.swing.JFrame {

    public billingInfoUI() {
        initComponents();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        hoursWorked = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        flatRate = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        workType = new javax.swing.JList();
        jScrollPane2 = new javax.swing.JScrollPane();
        jList2 = new javax.swing.JList();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jComboBox1 = new javax.swing.JComboBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Billing Information", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.ABOVE_BOTTOM, new java.awt.Font("Bleeding Cowboys", 0, 48))); // NOI18N

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 457, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );

        hoursWorked.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        hoursWorked.setText("Hours Worked");
        hoursWorked.setBorder(null);

        jLabel1.setText("Or");

        flatRate.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        flatRate.setText("Flat Rate");
        flatRate.setBorder(null);

        workType.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), "Work Type", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.TOP));
        workType.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Web Design", "Graphic Design", "Consulting" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        workType.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane1.setViewportView(workType);

        jList2.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), "Any Extras?", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.TOP));
        jList2.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Blog", "Forum", "Templating", "Rush Delivery" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        jScrollPane2.setViewportView(jList2);

        jButton1.setText("Save");
        jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButton1MouseClicked(evt);
            }
        });

        jButton2.setText("Invoice");

        jButton3.setText("Close");
        jButton3.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButton3MouseClicked(evt);
            }
        });
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jComboBox1.setModel(customers);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(89, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(hoursWorked, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(48, 48, 48)
                        .addComponent(jLabel1)
                        .addGap(1, 1, 1))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 142, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(31, 31, 31)))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(49, 49, 49)
                        .addComponent(flatRate, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(79, 79, 79))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(62, 62, 62)
                .addComponent(jButton1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 103, Short.MAX_VALUE)
                .addComponent(jButton2)
                .addGap(79, 79, 79)
                .addComponent(jButton3)
                .addGap(52, 52, 52))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(134, Short.MAX_VALUE)
                .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 238, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(107, 107, 107))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(30, 30, 30)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(hoursWorked, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(flatRate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addGap(20, 20, 20)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 40, Short.MAX_VALUE)
                .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(51, 51, 51)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton2)
                    .addComponent(jButton3)
                    .addComponent(jButton1))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                        

    }                                        

    private void jButton3MouseClicked(java.awt.event.MouseEvent evt) {                                      
        new FreelanceBillingUI().setVisible(true);
        setVisible(false);
    }                                    

    private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {                                      
String hoursWorkedtxt = hoursWorked.getText();
String flatRatetxt = flatRate.getText();
workType.getSelectedValue();
workType.toString();
Object workTypetxt = workType.getSelectedValue();

if(hoursWorkedtxt.contains("H")){
hoursWorkedtxt = "0";
}else{
flatRatetxt = "0";
}



    }                                    


public class CustomerData {


    private static final String JDBC_CONNECTION_URL    = "jdbc:mysql://localhost/test";

    private static final String DATABASE_USER         = "root";

    private static final String DATABASE_PASSWORD    = "root";

    private static final String SQL_FETCH_CUSTOMERS = "SELECT custName FROM customers";

    private Connection connection = null;


    public CustomerData(){
        initConnection();
    }


    private void initConnection() {
        try {
            //load the mysql driver
            Class.forName("com.mysql.jdbc.Driver");
            //create the database connection
            connection = DriverManager.getConnection(JDBC_CONNECTION_URL, DATABASE_USER, DATABASE_PASSWORD);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    public void closeConnection(){
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                connection = null;
            }
        }
    }

    public ArrayList fetchCustomerData(){
        if (connection != null){
            Statement statement = null;
            try {
                statement = connection.createStatement();
                ResultSet resultSet = statement.executeQuery(SQL_FETCH_CUSTOMERS);
                return convertResultSetToCustomersArray(resultSet);
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {

                if (statement != null){
                    try {
                        statement.close();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }
            }
        }else{
            System.out.println("NO VALID DATABASE CONNECTION, CAN'T FETCH CUSTOMER DATA!");
        }
        return new ArrayList();
    }

    private ArrayList convertResultSetToCustomersArray(ResultSet results) throws SQLException{
        ArrayList customers = new ArrayList();

        while (results.next()){
            customers.add(results.getString("custName"));
        }
        return customers;
    }
}

    private void initData(){
        CustomerData customerData = new CustomerData();

        ArrayList custArrayList = customerData.fetchCustomerData();

        customers = (String[]) custArrayList.toArray(new String[0]);
    }

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new billingInfoUI().setVisible(true);
            }
        });
    }
    private String[] customers = null;
    private javax.swing.JTextField flatRate;
    private javax.swing.JTextField hoursWorked;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JList jList2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JList workType;


}

2 个答案:

答案 0 :(得分:5)

有太多代码可供查看,其中90%与在组合框中添加数据无关。你有十几个其他组件使代码混乱,所以我们无法看到comobo框实际发生了什么。

您真的需要帮助,然后发布SSCCE

即创建一个简单的框架并将硬编码数据加载到组合框中。

然后创建一个简单的程序来从数据库中读取数据,并使用System.out.println(...)来显示每个值。

一旦掌握了两个基本步骤,就将两个程序放在一起,从数据库中动态加载组合框。

最后将其余的组件添加到框架中。

将问题分解为小的,可管理的步骤,您将能够更轻松地调试它。

答案 1 :(得分:1)

几点:

  • 在您的代码中,我看不到在任何地方发出initData的电话。没有那个调用,你就不会调用你的数据库代码。没有数据库调用,您将无法获取数据。
  • JComboBox没有采用数组的setModel方法。您可以将数组包装在DefaultComboBoxModel中并在模型上进行设置。
  • 最好记住,不应在AWT绘制线程中进行数据库访问等阻塞调用,并且在AWT线程之外进行更新GUI的调用也不应该。您应该考虑创建GUI并在单独的线程中获取数据,并使用SwingUtlities.invokeLater或类似工具来更新GUI。