Interview Questions

Java Keywords
Key Concepts
OOPS in java
Java Collections#1
Java Collections #2
Exceptions #1
Exceptions #2
Threads#1
Threads#2
InnerClass
Serialization
Immutable Class
Cloning in Java
Garbage Collection
JSP #1
JSP #2
Programming Q#1
Programming Q#2
Programming Q#3


Jtable takes 2D array as an argument to fill it. Sometime its difficult to convert a list of objects into a 2D array and its waste of time and work also. To avoid this one can play with the DefaultTableModel object and set it as property of the JTable.The example is as follows.
Consider I have a class Word_Analysis which contains following parameters.

 
 class Word_Analysis {
    boolean isAllCap;
    String word;
    int length;
    boolean isInitialCap;
    boolean isRoman;
    boolean isDigit;
    //create getter and setters
 }
    

 To display the records of Entity objects , an object of DetaultTableModel has to be created and set it to table. Some methods need to be overloaded and its mandatory to do it. Below code is the minimum methods required.

 
    
    class TableModel extends AbstractTableModel{
    List wordsList;
    String headerList[] = new String[]{"€œCol1"€,"€Col2"€,"€Col3"€,"€Col4"€,"€Col5"€};
    public TableModel(List list){
     wordsList = list;
    }
 @Override
    public int getColumnCount() {
      return 5;
    }
 @Override
 public int getRowCount(){
        return wordsList.size();
       }
    // this method is called to set the value of each cell
 @Override
        public Object getValueAt(int row, int column) {
     Word_Analysis entity = null;
          Word_Analysis entity = wordsList.get(row);
          switch (column) {
			case 0:
			    return entity.word;     
			case 1:
				return entity.length;
			case 2:
				return entity.isAllCap();
			case 3:
				return entity.isIntialCap();
			case 4:
				return entity.isDigit();
			case 5:
				return entity.isRoman();
		}
       //display the name of columns
		public String getColumnName(int col) {
			headerList[col];     
		}
    }

Once the model class is created create the model object and Once the model class is created create the model object and set it to table public

 
        class DisplayTable{
			public static void main(String args[]){
			List entityList = new ArrayList();
			//set the entity objects in the list
			JFrame frame = new JFrame();
			JTable table = new JTable();
			AbstractTableModel model = new TableModel(entityList);
			JScrollPane scrollPane = new JScrollPane(table);
			table.setModel(model);
			frame.getContentPane().add(scrollPane, BorderLayout.CENTER);
			frame.pack();
			frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
			frame.setVisible(true);
			} 
		}