JTable Component in Java

May 31, 2020
Tutorials
jtable in java

In this tutorial, we will be going to create a program that has the JCheckBox Component using Java. The JTable is used to display tables of data that allows the user to edit the data. This is mainly used to view data from the database.

Let’s start this tutorial!

1. Open JCreator or NetBeans and make a java program with a file name of jTableComponent.java.

2. Import the javax.swing package to access the JFrame, JScrollPane, the JTable class.

import javax.swing.*;

3. Initialize your variable in your Main, variable frame for creating JFrame, variable table for JTable, and variable scrollPane for JScrollPane. We will create an object array for the rows and columns that will be put this data to the JTable.

JFrame frame = new JFrame("JTable Component");
 
 
Object rows[][] = { { "0001", "Lyndon", "Bermoy" },
    { "0002", "Jonah", "Juarez" } };
Object columns[] = { "Student ID", "First name", "Last name" };
 
JTable table = new JTable(rows, columns);
JScrollPane scrollPane = new JScrollPane(table);

As we can see in the code above, we have created an object rows that is a multidimensional array specifically a two-dimensional one. The object columns had three columns on it as is a one-dimensional array only. The syntax for the JTable is JTable(row,column). The JTable above is placed inside of a JScrollPane. By default, a JTable will adjust its width such that a horizontal scrollbar is unnecessary.

4. Add the JScrollPane variable instead of the table variable of JTable for JTable to the frame using the default BorderLayout of the center position of the getContentPane method because the JTable is inside of the JScrollPane component. Copy this code below:

frame.getContentPane().add(scrollPane, "Center");

5. Finally, set the size, visibility, and the close operation of the frame.

frame.setSize(300, 150);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Output:

jtable in java

Here’s the full source code of this tutorial:

import javax.swing.*;
 
 
public class jTableComponent {
  public static void main(String args[]) {
    JFrame frame = new JFrame("JTable Component");
 
 
    Object rows[][] = { { "0001", "Lyndon", "Bermoy" },
       { "0002", "Jonah", "Juarez" } };
    Object columns[] = { "Student ID", "First name", "Last name" };
 
    JTable table = new JTable(rows, columns);
    JScrollPane scrollPane = new JScrollPane(table);
 
 
    frame.getContentPane().add(scrollPane, "Center");
 
    frame.setSize(300, 150);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 
  }
}

 

Facebook Comments

Leave a Reply

Your email address will not be published.