JTable Example Java Swing

JTable displays data in horizontal and vertical columns in a two-dimensional format. The table can be resized or moved. Here, table is created and added to a scroll pane. In turn, scroll pane is added to the container.

We create a JTable and add it to a scroll pane. Then, scroll pane is added to the container.

import java.awt.*;    
import java.awt.event.*;   
import javax.swing.* ;
public class JTableDemo extends JApplet   
{
  public void init()   
  {
    Container c = getContentPane();
    c.setLayout( new BorderLayout()) ;
 
    String fields[] = { "empid",  "empname",  "empsal" } ;

    Object details[][] = {{ "1", "S N Rao", "4500.50" },                  // instead of Object array
                                           { "2","S umathi","4567.50" },  // String array can also be used
                                           { "3", "Sridhar", "2246.30" },
                                           { "4", "Jyothi", "3245.75" },
                                           { "5", "Jyostna", "2500.25" }   
                         };

    JTable jt = new JTable(details, fields);

    int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;             // if the rows are more than         
    int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;           // height of the applet,     
    JScrollPane jsp = new JScrollPane(jt , v , h); 	                  // scroll bar is added
    c.add(jsp, "Center");
  }
}

Following is the HTML file to run the above JApplet




JTable
Output screen on JTable Example

JTable jt = new JTable(details, fields);

The JTable constructor takes the column data and column headers as parameters. The columns in JTable can be slided by dragging the column name.

Other options for ScrollPaneConstants:
ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER;
ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS;

Similarly for horizontal scroll bar also.

Leave a Comment

Your email address will not be published.