Archive for Programming

How to populate JTable with records from database in Java?

public class PopulateTableFromDb extends JFrame{
    public static void main(String args[]) {
        new PopulateTableFromDb();
    }
    
    public PopulateTableFromDb() {        
       String[][] rowData = readDB();
       String columnNames[] = { "Name", "Phone", "Address" };
       JTable table = new JTable(rowData, columnNames);
       JScrollPane scrollPane = new JScrollPane(table);
       
       getContentPane().setLayout(new GridLayout(0, 1));
       add(scrollPane, BorderLayout.CENTER);
       
       setVisible(true);
       setSize(400, 400);
       setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    
    private static String[][] readDB() {
        Connection connect;
        String Username="root";
        String Password="";
        String URL="jdbc:odbc:phonebook";
        int i = 0;
        String[][] storeData = new String[10][3];
            
        try {
            connect = DriverManager.getConnection(URL,Username,Password);
            Statement st = connect.createStatement();
            ResultSet rs = st.executeQuery("SELECT * FROM phonebook");

            while(rs.next())
            {
               String[] temp = new String[10];
               temp[0] = rs.getString("name");
               temp[1] = rs.getString("phone");
               temp[2] = rs.getString("address");
               
               storeData[i] = temp;
               i++;
            }     
        } 
        catch(SQLException e) {
            System.out.println("Error");
        } 
        
        return storeData;
    }
}

Distinct Validation using jQuery Validation

Using jquery validation is easier and much of a common practice which will take off the burden of validating bunch of form fields. The power of jquery validation comes into play where it allows us to write a custom validation methods and classes.

I was looking into using this power of custom methods for distinct validation for the bunch of form fields I was working on, when I came accross this site which illustrates the way of doing so. We could add our custom function/method which does the required validation for us and we could use this function in similar fashion as to other inbuilt jquery validation methods. Simple as that, Isn’t it? If not try sometime, It would be 🙂

jQuery.validator.addMethod("distinctValue", function(value, element, options) {
// get all the elements passed here with the same class
    var elems = $(element).parents('form').find(options[0]);
// the value of the current element
var valueToCompare = value;
// count
var matchesFound = 0;
// loop each element and compare its value with the current value
// and increase the count every time we find one
jQuery.each(elems, function(){
thisVal = $(this).val();
if(thisVal == valueToCompare){
matchesFound++;
}
});
// count should be either 0 or 1 max
if(this.optional(element) || matchesFound <= 1) {
        elems.removeClass('error');
        return true;
    } else {
        elems.addClass('error');
    }
}, jQuery.format("Please enter a Unique Value."));

So, this is the method that we have added which will check for distinct value with the matched class name that we pass as an argument. One advantage of using classname is we could use this validation for any number of fields that we wanted. The html form field should be fairly simple with only requiring the classname that we will be passing in above method.

<form name="customForm" id="customForm">
<p>
    <label for="field1">Field 1</label>
    <input id="field1" name="field1" class="distinctField" />
</p>
<p>
   <label for="field2">Field 2 </label>
   <input id="field2" name="field2" class="distinctField" />
</p>
</form>

Now, we will be using the regular jquery validation rules and methods with our custom method. We will be passing the classname for our custom method.

$("#customForm").validate({
 rules: {
      field1:{
           required: true,
           distinctValue: ['.distinctField']
      },
      field2:{
          required: true,
          distinctValue: ['.distinctField']
      }
 }
});
www.000webhost.com