简体   繁体   English

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

[英]Cannot show the results from the database using a JList

This got to be an easy fix. 这必须很容易解决。 I have been trying all day yesterday, and I cannot get this thing working.I cannot fetch data from a database and show it in a JList. 昨天我整天都在努力,但我无法正常工作,无法从数据库中获取数据并将其显示在JList中。 Normally, I separate the classes in different files, but for the purpose of me to learn Java, I put everything in one file. 通常,我将类分开放在不同的文件中,但是为了学习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);



}


}

Do list = new JList(model); list = new JList(model); at the end, with the model filled. 最后,填充模型。


* Another attempt: This time with first(). * 另一尝试:这次使用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());
    }

}
  1. verify that the SQL portion works correctly. 验证SQL部分是否正常工作。 Try a System.out.println() in the while(rows.next()) loop. while(rows.next())循环中尝试System.out.println()。
  2. After the loop completes, query the model for its size. 循环完成后,查询模型的大小。 If it is zero, you have a problem. 如果为零,则有问题。
  3. If the model is not empty, but the JList doesn't show anything, verify that the model actually fires the correct events (it should, since you are using unchanged DefaultListModel, but in custom implementations you might forget to fire the events) when data changes. 如果模型不为空,但是JList不显示任何内容,请验证模型是否在数据真实时触发正确的事件(由于您使用的是DefaultListModel,所以应该触发正确的事件,但是在自定义实现中,您可能会忘记触发事件)变化。 For this you can add a ListModelListener to the model and have it print out whenever an event is fired. 为此,您可以将ListModelListener添加到模型中,并在触发事件时将其打印出来。
  4. Check the JList itself. 检查JList本身。 Is it disabled? 是残疾人吗? Are you doing anything to it that would prevent it from displaying data? 您是否正在采取任何措施阻止它显示数据? Strip off any customization code and start with a plain panel.add(new JList(myModel)) and go from there. 剥离所有自定义代码,并从一个普通的panel.add(new JList(myModel)) ,然后从那里开始。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM