JTable example
package com.ack.gui.swing.simple;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.*;
public class JTableExample extends JFrame {
String data[][] = {{"John", "Sutherland", "Student"},
{"George", "Davies", "Student"},
{"Melissa", "Anderson", "Associate"},
{"Stergios", "Maglaras", "Developer"},
};
String fields[] = {"Name", "Surname", "Status"};
public static void main( String[] argv ) {
JTableExample myExample = new JTableExample( "JTable Example" );
}
public JTableExample( String title ) {
super( title );
setSize( 150, 150 );
addWindowListener( new WindowAdapter() {
public void windowClosing( WindowEvent we ) {
dispose();
System.exit( 0 );
}
} );
init();
pack();
setVisible( true );
}
private void init() {
JTable jt = new JTable( data, fields );
JScrollPane pane = new JScrollPane( jt );
getContentPane().add( pane );
}
}
Listing 1: Code for Simple JTable.
import com.sun.java.swing.*;
import com.sun.java.swing.table.*;
public class SimpleTableTest extends JFrame {
public SimpleTableTest() {
setLocation(100,100);
setSize(250,100);
String[][] data = { {"eggs", "sandwich", "steak", "snickers"},
{"bacon", "pickles", "potato", "apple"},
{"syrup", "mayo", "corn", "banana"},
{"pancakes", "chips", "broccoli", "crunch bar"},
{"sausage", "pizza", "pie", "protein shake"}};
String[] headers = {"Breakfast", "Lunch", "Dinner", "Snack"};
DefaultTableModel model = new DefaultTableModel(data, headers);
JTable table = new JTable(model);
getContentPane().add(table);
setVisible(true);
}
public static void main(String[] args) {
SimpleTableTest simpleTableTest = new SimpleTableTest();
}
}
Description of code:
JTable( Object data[][], Object col[]):
This is the constructor of JTable class that implements a JTable for displaying the values in tabular
format like rows and columns. All rows must have the same length as column names. It takes two
arguments: data and col.
data - It defines the all data that will have to create a JTable.
col - It specifies the name of each column of the JTable.
Here is the code of program:
import javax.swing.*;
import java.awt.*;
public class JTableComponent{
public static void main(String[] args)
{
new JTableComponent();
}
public JTableComponent(){
JFrame frame = new JFrame("Creating
JTable Component Example!");
JPanel panel = new JPanel();
String data[][] = {{"vinod","BCA","A"},{"Raju","MCA","b"},
{"Ranjan","MBA","c"},{"Rinku","BCA","d"}};
String col[] = {"Name","Course","Grade"};
JTable table = new JTable(data,col);
panel.add(table,BorderLayout.CENTER);
frame.add(panel);
frame.setSize(300,200);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}