无法使用 JList 显示数据库中的结果



这必须很容易解决。我昨天已经尝试了一整天,我无法让这个东西工作。我无法从数据库中获取数据并将其显示在 JList 中。通常,我将类分开在不同的文件中,但为了学习Java,我将所有内容放在一个文件中。

public class Window extends JFrame{
private static final long serialVersionUID = 1L;
// declare global text fields
private JTextField txtCustomerID;
private JTextField txtFirstName;
private JTextField txtLastName;
private JTextField txtMiddleInitial;
private JTextField txtStreet;
private JTextField txtCity;
private JTextField txtState;
private JTextField txtZip;
private JTextField txtPhone;
private JTextField txtEmail;
private JTextField txtSearch;
// declare global list
private static JList list;
private String[] results;
private DefaultListModel model;
// declare global labels
private JLabel labFirstName;
private JLabel labLastName;
private JLabel labMiddleInitial;
private JLabel labStreet;
private JLabel labCity;
private JLabel labState;
private JLabel labZip;
private JLabel labPhone;
private JLabel labEmail;
// declare global buttons
private JButton newCustomer;
private JButton open;
private JButton update;
private JButton cancel;
private JButton remove;
private JButton search;
// function that adds components to GridBagConstraints Layout Manager
private void addComponent(JPanel panel, JComponent theComponent, int xPos, int yPos, int compWidth, int compHeight, int place, int stretch, boolean useScrollPane){
    GridBagConstraints gbc = new GridBagConstraints();
    gbc.gridx = xPos;
    gbc.gridy = yPos;
    gbc.gridwidth = compWidth;
    gbc.gridheight = compHeight;
    gbc.weightx = 100;
    gbc.weighty = 100;
    gbc.insets = new Insets(2,2,2,2);
    gbc.anchor = place;
    gbc.fill = stretch;
    if(useScrollPane){
        JScrollPane scrollPane = new JScrollPane(theComponent);
        scrollPane.setPreferredSize(new Dimension(400, 200));
        panel.add(scrollPane, gbc);
    } else {
        panel.add(theComponent, gbc);
    }
}
// function that adds components to panel
private void addComponent2(JPanel panel, JComponent theComponent){
    panel.add(theComponent);
}

// function that connects and tests to the database
private void insertDatabase(){
    try {
        Connection connect = null;
        Class.forName("com.mysql.jdbc.Driver");
        String url = "";
        String user = "";
        String password ="";
        connect = DriverManager.getConnection(url,user,password);
        Statement SQLStatement = connect.createStatement();
        String insert = "INSERT INTO customerinfo(FirstName," +
                "LastName, MiddleInitial, Street, City, State, ZipCode, Phone, Email) VALUES('"+ txtFirstName.getText() +"', " +
                        "'" + txtLastName.getText() +"', '" + txtMiddleInitial.getText() +"', '" + txtStreet.getText() +"', " +
                                "'" + txtCity.getText() +"', '" + txtState.getText() +"', '" + Integer.parseInt(txtZip.getText()) +"'" +
                                ", '" + txtPhone.getText() +"', '" + txtEmail.getText() +"')";
        SQLStatement.execute(insert);
        connect.close();
    } catch (ClassNotFoundException e) {
        JOptionPane.showMessageDialog(this, "Where is your Mysql JDBC Driver?");
        e.printStackTrace();
    } catch (SQLException e){
        JOptionPane.showMessageDialog(this, "SQLException: " + e.getMessage());
        JOptionPane.showMessageDialog(this, "VendorError: " + e.getErrorCode());
    }
}

// function that checks for empty fields
private void checkForEmptyFields(){
    String[] labValues = {labFirstName.getText(), labLastName.getText(), labMiddleInitial.getText(),
            labStreet.getText(), labCity.getText(), labState.getText(), labZip.getText(), 
            labPhone.getText(), labEmail.getText()};
    String[] values = {txtFirstName.getText(), txtLastName.getText(),
            txtMiddleInitial.getText(), txtStreet.getText(), txtCity.getText(),
            txtState.getText(), txtZip.getText(), txtPhone.getText(), txtEmail.getText()};
    for(int i=0; i<values.length; i++){
        if(values[i].length() == 0){
            JOptionPane.showMessageDialog(this, labValues[i].replace(":", "") + " field is empty");
        }
    }
}
// function that will update a field in the database
private void updateDatabase(){
    try {
        Connection connect = null;
        Class.forName("com.mysql.jdbc.Driver");
        String url = "";
        String user = "";
        String password ="";
        connect = DriverManager.getConnection(url,user,password);
        Statement SQLStatement = connect.createStatement();
        String update = "UPDATE customerinfo SET FirstName='" + txtFirstName.getText() +"', LastName='" + txtLastName.getText() +"', " +
                "MiddleInitial='"+ txtMiddleInitial.getText() +"', Street='"+ txtStreet.getText() +"', City='"+ txtCity.getText() +"', " +
                "State='"+ txtState.getText() +"', ZipCode='"+ txtZip.getText() +"', Phone='"+ txtPhone.getText() +"', " +
                "Email='"+ txtEmail.getText() +"'" +
                "WHERE CustomerID='"+ txtCustomerID.getText() +"'";
        SQLStatement.execute(update);
    } catch (ClassNotFoundException e) {
        JOptionPane.showMessageDialog(this, "Where is your Mysql JDBC Driver?");
        e.printStackTrace();
    } catch (SQLException e){
        JOptionPane.showMessageDialog(this, "SQLException: " + e.getMessage());
        JOptionPane.showMessageDialog(this, "VendorError: " + e.getErrorCode());
    }
}
// function that will delete a record from the database
private void deleteRecord(){
    try {
        Connection connect = null;
        Class.forName("com.mysql.jdbc.Driver");
        String url = "";
        String user = "";
        String password ="";
        connect = DriverManager.getConnection(url,user,password);
        Statement SQLStatement = connect.createStatement();
        String delete = "DELETE FROM customerinfo WHERE CustomerID='"+ txtCustomerID.getText() +"'";
        SQLStatement.execute(delete);
        connect.close();
    } catch (ClassNotFoundException e) {
        JOptionPane.showMessageDialog(this, "Where is your Mysql JDBC Driver?");
        e.printStackTrace();
    } catch (SQLException e){
        JOptionPane.showMessageDialog(this, "SQLException: " + e.getMessage());
        JOptionPane.showMessageDialog(this, "VendorError: " + e.getErrorCode());
    }
}
// function that will search for records in the database
private void searchRecord(){
    model = new DefaultListModel();
    list = new JList(model);
    list.setVisibleRowCount(3);
    list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    //list.setFixedCellHeight(27);
    //list.setFixedCellWidth(130);
    try {
        model.clear();
        Connection connect = null;
        Class.forName("com.mysql.jdbc.Driver");
        String url = "";
        String user = "";
        String password ="";
        connect = DriverManager.getConnection(url,user,password);
        Statement SQLStatement = connect.createStatement();
        String select = "SELECT * FROM customerinfo WHERE LastName LIKE '"+ txtSearch.getText().trim() +"%'";
        ResultSet rows = SQLStatement.executeQuery(select);
        while(rows.next()){
            model.addElement(rows.getString("FirstName") + "n");
            System.out.print(model.toString() + "n");
        }

            System.out.print(model.getSize());
            rows.close();
            SQLStatement.close();
            connect.close();
            txtSearch.setText("");
    } catch (ClassNotFoundException e) {
        JOptionPane.showMessageDialog(this, "Where is your Mysql JDBC Driver?");
        e.printStackTrace();
    } catch (SQLException e){
        JOptionPane.showMessageDialog(this, "SQLException: " + e.getMessage());
        JOptionPane.showMessageDialog(this, "VendorError: " + e.getErrorCode());
    }
}
// function that clear fields once register
private void clearFields(){
    txtFirstName.setText("");
    txtLastName.setText("");
    txtMiddleInitial.setText("");
    txtStreet.setText("");
    txtCity.setText("");
    txtState.setText("");
    txtZip.setText("");
    txtPhone.setText("");
    txtEmail.setText("");
}
// Implement Action Listener
private class handler implements ActionListener{
    @Override
    public void actionPerformed(ActionEvent e) {
        // if user clicks on New Customer Button, do the following...
        if(e.getSource() == newCustomer){
            checkForEmptyFields();
            insertDatabase();
            clearFields();
        } else if(e.getSource() == update){
            checkForEmptyFields();
            updateDatabase();
            clearFields();
        } else if(e.getSource() == remove){
            checkForEmptyFields();
            deleteRecord();
            clearFields();
        } else if(e.getSource() == cancel){
            clearFields();
        } else if(e.getSource() == open){
        } else if(e.getSource() == search){
            searchRecord();
        } 
    }
}
private class selectRow implements ListSelectionListener{
    @Override
    public void valueChanged(ListSelectionEvent event) {
        if(!event.getValueIsAdjusting()){
            String selection = list.getSelectedValue().toString();
        }
    }
}
// window constructor
public Window(){
    JPanel theMainPanel = new JPanel(new BorderLayout());
    JPanel thePanel = new JPanel();
    thePanel.setLayout(new GridBagLayout());
    JTabbedPane tabbedPane = new JTabbedPane();

    JLabel labCustomerID = new JLabel("Customer ID:");
    addComponent(thePanel, labCustomerID, 0, 0, 1, 1, GridBagConstraints.WEST, GridBagConstraints.NONE, false);
    txtCustomerID = new JTextField(24);
    txtCustomerID.setEnabled(false);
    txtCustomerID.setBackground(Color.LIGHT_GRAY);
    addComponent(thePanel, txtCustomerID, 1, 0, 1, 1, GridBagConstraints.WEST, GridBagConstraints.NONE, false);
    open = new JButton("Open");
    addComponent(thePanel, open, 1, 0, 1, 1, GridBagConstraints.EAST, GridBagConstraints.NONE, false);
    labFirstName = new JLabel("First Name:");
    addComponent(thePanel, labFirstName, 0, 1, 1, 1, GridBagConstraints.WEST, GridBagConstraints.NONE, false);
    txtFirstName = new JTextField(30);

    addComponent(thePanel, txtFirstName, 1, 1, 1, 1, GridBagConstraints.EAST, GridBagConstraints.NONE, false);
    labLastName = new JLabel("Last Name:");
    addComponent(thePanel, labLastName, 0, 3, 1, 1, GridBagConstraints.WEST, GridBagConstraints.NONE, false);
    txtLastName = new JTextField(30);
    addComponent(thePanel, txtLastName, 1, 3, 1, 1, GridBagConstraints.EAST, GridBagConstraints.NONE, false);
    labMiddleInitial = new JLabel("Middle Initial:");
    addComponent(thePanel, labMiddleInitial, 0, 4, 1, 1, GridBagConstraints.WEST, GridBagConstraints.NONE, false);
    txtMiddleInitial = new JTextField(30);
    addComponent(thePanel, txtMiddleInitial, 1, 4, 1, 1, GridBagConstraints.WEST, GridBagConstraints.NONE, false);
    labStreet = new JLabel("Street:");
    addComponent(thePanel, labStreet, 0, 5, 1, 1, GridBagConstraints.WEST, GridBagConstraints.NONE, false);
    txtStreet = new JTextField(30);
    addComponent(thePanel, txtStreet, 1, 5, 1, 1, GridBagConstraints.EAST, GridBagConstraints.NONE, false);
    labCity = new JLabel("City:");
    addComponent(thePanel, labCity, 0, 6, 1, 1, GridBagConstraints.WEST, GridBagConstraints.NONE, false);
    txtCity = new JTextField(30);
    addComponent(thePanel, txtCity, 1, 6, 1, 1, GridBagConstraints.EAST, GridBagConstraints.NONE, false);
    labState = new JLabel("State:");
    addComponent(thePanel, labState, 0, 7, 1, 1, GridBagConstraints.WEST, GridBagConstraints.NONE, false);
    txtState = new JTextField(30);
    addComponent(thePanel, txtState, 1, 7, 1, 1, GridBagConstraints.EAST, GridBagConstraints.NONE, false);
    labZip = new JLabel("Zip Code:");
    addComponent(thePanel, labZip, 0, 8, 1, 1, GridBagConstraints.WEST, GridBagConstraints.NONE, false);
    txtZip = new JTextField(5);
    addComponent(thePanel, txtZip, 1, 8, 1, 1, GridBagConstraints.WEST, GridBagConstraints.NONE, false);
    labPhone = new JLabel("Phone:");
    addComponent(thePanel, labPhone, 0, 9, 1, 1, GridBagConstraints.WEST, GridBagConstraints.NONE, false);
    txtPhone = new JTextField(30);
    addComponent(thePanel, txtPhone, 1, 9, 1, 1, GridBagConstraints.EAST, GridBagConstraints.NONE, false);
    labEmail = new JLabel("Email:");
    addComponent(thePanel, labEmail, 0, 10, 1, 1, GridBagConstraints.WEST, GridBagConstraints.NONE, false);
    txtEmail = new JTextField(30);
    addComponent(thePanel, txtEmail, 1, 10, 1, 1, GridBagConstraints.EAST, GridBagConstraints.NONE, false);
    this.add(thePanel, BorderLayout.NORTH);
    JPanel thePanel2 = new JPanel();
    thePanel2.setLayout(new FlowLayout(FlowLayout.RIGHT));
    newCustomer = new JButton("New Customer");
    addComponent2(thePanel2, newCustomer);
    update = new JButton("Update");
    addComponent2(thePanel2, update);
    remove = new JButton("Remove");
    addComponent2(thePanel2, remove);
    cancel = new JButton("Cancel");
    addComponent2(thePanel2, cancel);
    this.add(thePanel2, BorderLayout.CENTER);
    JPanel thePanel3 = new JPanel(new GridBagLayout());
    thePanel3.setBorder(BorderFactory.createTitledBorder("Customer Action"));
    JLabel labSearch = new JLabel("Search By Last Name:");
    addComponent(thePanel3, labSearch, 0, 0, 1, 1, GridBagConstraints.WEST, GridBagConstraints.NONE, false);
    txtSearch = new JTextField(15);
    addComponent(thePanel3, txtSearch, 1, 0, 1, 1, GridBagConstraints.WEST, GridBagConstraints.NONE, false);
    search = new JButton("Search");
    addComponent(thePanel3, search, 2, 0, 1, 1, GridBagConstraints.EAST, GridBagConstraints.NONE, false);
    //JScrollPane scrollPane = new JScrollPane(list);
    //scrollPane.setPreferredSize(new Dimension(400,200));
    addComponent(thePanel3, list, 0, 1, 3, 1, GridBagConstraints.CENTER, GridBagConstraints.NONE, true);
    this.add(thePanel3, BorderLayout.SOUTH);

    theMainPanel.add(thePanel, BorderLayout.NORTH);
    theMainPanel.add(thePanel2, BorderLayout.CENTER);
    theMainPanel.add(thePanel3, BorderLayout.SOUTH);

    tabbedPane.addTab("Customer Info", theMainPanel);
    this.add(tabbedPane);

    handler listen = new handler();
    newCustomer.addActionListener(listen);
    update.addActionListener(listen);
    remove.addActionListener(listen);
    cancel.addActionListener(listen);
    search.addActionListener(listen);

}

}
  1. 验证 SQL 部分是否正常工作。在while(rows.next())循环中尝试 System.out.println()。
  2. 循环完成后,查询模型的大小。如果为零,则有问题。
  3. 如果模型不为空,但 JList 未显示任何内容,请验证模型在数据更改时是否实际触发了正确的事件(它应该触发,因为您使用的是未更改的 DefaultListModel,但在自定义实现中,您可能会忘记触发事件)。为此,您可以向模型添加一个 ListModelListener,并在触发事件时将其打印出来。
  4. 检查 JList 本身。是否禁用?您是否对它做了任何会阻止它显示数据的事情?剥离任何自定义代码,从普通panel.add(new JList(myModel))开始,然后从那里开始。

最后执行list = new JList(model);,并填充模型。


*另一次尝试:这次使用 first()。

private void searchRecord() {
    model = new DefaultListModel();
    try {
        Connection connect = null;
        Class.forName("com.mysql.jdbc.Driver");
        String url = "";
        String user = "";
        String password ="";
        connect = DriverManager.getConnection(url,user,password);
        Statement sqlStatement = connect.createStatement();
        String select = "SELECT FirstName, LastName "
            + "FROM customerinfo WHERE LastName LIKE '" +  txtSearch.getText().trim() + "%' "
            + "ORDER BY FirstName, LastName";
        ResultSet rows = sqlStatement.executeQuery(select);
        if (rows.first()) {
            do {
                model.addElement(rows.getString("FirstName"));
            } while (rows.next());
        }
        rows.close();
        sqlStatement.close();
        connect.close();
        txtSearch.setText("");
        list = new JList(model);
        list.setVisibleRowCount(3);
        list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    } catch (ClassNotFoundException e) {
        JOptionPane.showMessageDialog(this, "Where is your Mysql JDBC Driver?");
        e.printStackTrace();
    } catch (SQLException e){
        JOptionPane.showMessageDialog(this, "SQLException: " + e.getMessage());
        JOptionPane.showMessageDialog(this, "VendorError: " + e.getErrorCode());
    }
}

最新更新