Practical 8: Write a program to create a JTable.

1) Develop a program to demonstrate the use of JTable.
Ans:
import javax.swing.*;
import java.awt.*;
import javax.swing.table.*;

public class JTableDemo 
{
    public static void main(String[] args) {
        
        JFrame JFrameMain = new JFrame();
        JFrameMain.setVisible(true);
        JFrameMain.setSize(400,400);


        String colHeads[] = {"ID","Name","Salary"};

        Object data[][] = {
            {101,"Amit",670000},
            {102,"Jai",780000},
            {101,"Sachin",700000}
        };
        JTable JTableObj = new JTable(data,colHeads);

        int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
        int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
        JScrollPane jsp = new JScrollPane(JTableObj,v,h);

        JFrameMain.add(jsp,BorderLayout.CENTER);
        
        //JFrameMain.add(JTableObj);
    }
}


Output:
JTable in Swing

2) Write a program to create a table of Name of Student, Percentage and Grade of 10 students using JTable.
Ans:
// Program to create a table of Name of Student, Percentage and Grade of 10Student
import java.awt.BorderLayout;
import javax.swing.JApplet;
import javax.swing.JTable;
import javax.swing.ScrollPaneConstants;
import javax.swing.JScrollPane;


public class JTableStudents  extends JApplet
{
    public void init()
    {
        setVisible(true);
        setSize(400,400);
        //setLayout( new BorderLayout() );
        
        String collumnHeading[] = {"Name","Percentage","Grade"};
        
        Object data[][]={
            {"A1",98,"A"},
            {"A2",90,"C"},
            {"A3",88,"A"},
            {"A4",99,"A"},
            {"A5",59,"A"},
            {"A6",94,"D"},
            {"A7",92,"A"},
            {"A8",42,"C"},
            {"A9",85,"A"},
            {"A10",98,"B"}
        };
        
        JTable JTableObj = new JTable(data,collumnHeading);

        int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
        int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
        JScrollPane jsp = new JScrollPane(JTableObj,v,h);

        add(jsp,BorderLayout.CENTER);
    }
}

/*
    
    
*/


Output:
JTable for 10 Students

Previous
Next Post »