import javax.swing.*; public class JTableExample1 extends JFrame { public JTableExample1() { // create data for the table Object[][] data = { {"John", 25, "Male"}, {"Mary", 30, "Female"}, {"Bob", 40, "Male"} }; // create column headers for the table String[] columnHeaders = {"Name", "Age", "Gender"}; // create a JTable with the data and column headers JTable table = new JTable(data, columnHeaders); // set the grid lines to be displayed table.setShowGrid(true); // add the table to the frame add(new JScrollPane(table)); setSize(300, 200); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); setVisible(true); } public static void main(String[] args) { new JTableExample1(); } }
import javax.swing.*; import javax.swing.table.DefaultTableModel; public class JTableExample2 extends JFrame { public JTableExample2() { // create column headers for the table String[] columnHeaders = {"Name", "Age", "Gender"}; // create a DefaultTableModel with the column headers DefaultTableModel model = new DefaultTableModel(columnHeaders, 0); // add data to the model Object[] data1 = {"John", 25, "Male"}; Object[] data2 = {"Mary", 30, "Female"}; Object[] data3 = {"Bob", 40, "Male"}; model.addRow(data1); model.addRow(data2); model.addRow(data3); // create a JTable with the model JTable table = new JTable(model); // set the grid lines to be displayed table.setShowGrid(true); // add the table to the frame add(new JScrollPane(table)); setSize(300, 200); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); setVisible(true); } public static void main(String[] args) { new JTableExample2(); } }In Example 2, a JTable is created using a DefaultTableModel with column headers. Data is added to the model using the addRow method. The setShowGrid method is called and set to true to display grid lines in the table. The table is added to a JScrollPane and then added to the JFrame. The library package for javax.swing is the Java Swing library.