Monday, April 23, 2012

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.



// declare global list
private static JList list;
//String[] results;
private DefaultListModel model;

// 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 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"));
}



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

}


Here is where I add the JList to thePanel3 and then to the JFrame:



addComponent(thePanel3, list, 0, 1, 3, 1, GridBagConstraints.CENTER, GridBagConstraints.NONE, true);
this.add(thePanel3, BorderLayout.SOUTH);
theMainPanel.add(thePanel3, BorderLayout.SOUTH);


Please help...I do not know how to work this!





No comments:

Post a Comment