Friday, 30 January 2015

A tutorial on JTable With Scroll Pane In Java

A table is a component that dislpays rows and columns of data.You can drag the cursor on column boundries to resize columns and also drag it to a new position.Tables are implemented by JTable class,which extends JComponent one of its construtor shown below.
JTable(data,colHeads)
Here data and colHeads array are represented by Two-dimensional array and one-dimensional array respectively.

CONSTRUCTORS OF JTABLE:

In this tutorial we have use above constructor but you can also create jtable using these constructor depending upon the codition,
JTable()
JTable(int rows,int col)
JTable(tablemodel)
JTable(Object [][] row data,Object[] colHeads)
JTable(Vector row,Vector colHeads)

If we create jtable with these constructors following points should be kept in mind.

  • All cells of table are editable.
  • It treat all data types as a same type (String).

CODING:

import javax.swing.*;
import java.awt.*;
class myjframe1 extends JFrame
{

public myjframe1()
{

setTitle("Simple example");
setSize(300, 200);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);      

String columnNames[] = { "NAME", "Phone", "Fax" };
String rowData[][] = { { "Gail", "4564", "3847" }
,{ "Anne", "789", "67389" }
,{ "Helen", "789", "67389"}
,{ "John", "7891", "67389"}
,{ "John", "7894", "67389"}
,{ "Erwin", "7839", "67389"}
,{ "Ken", "7829", "673893"}
,{ "Steve", "7289", "62738"}
,{ "Clark", "789", "67389"}
,{ "Matt", "7894", "67389"}
,{ "Edey", "7894", "677389"}

};
JTable table = new JTable(rowData, columnNames);
setLayout(new FlowLayout(FlowLayout.CENTER));
JScrollPane js = new JScrollPane(table,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
add(js);
}
}

class table
{
public static void main(String args[])
{
myjframe1 x= new myjframe1();
}
}

OUTPUT:



No comments:

Post a Comment