0

これは簡単に修正できます。私は昨日一日中試していましたが、これを機能させることができません.データベースからデータを取得してJListに表示することはできません. 通常はクラスごとにファイルを分けていますが、Java を学習する目的で、すべてを 1 つのファイルにまとめています。

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);



}


}
4

2 に答える 2

0
  1. SQL 部分が正しく機能することを確認します。while(rows.next())ループで System.out.println() を試してください。
  2. ループが完了したら、モデルのサイズをクエリします。ゼロの場合、問題があります。
  3. モデルが空ではなく、JList に何も表示されない場合は、データが変化します。このために、モデルに ListModelListener を追加し、イベントが発生するたびに出力することができます。
  4. JList自体を確認してください。無効になっていますか?データの表示を妨げる​​ようなことをしていますか? カスタマイズ コードを取り除き、プレーンから始めて、panel.add(new JList(myModel))そこから始めます。
于 2012-04-23T14:07:23.780 に答える
0

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());
    }

}
于 2012-04-23T13:43:51.183 に答える