Display Horizontal and Vertical Grid Lines in JTable



To display both horizontal and vertical grid lines in a table, use the setShowGrid() method and set it to true ?

The setShowGrid() method is used in graphical user interfaces or data visualization tools to control the visibility of grid lines in a component, like a chart or a table.

table.setShowGrid(true);

JTable is a class in the Java Swing library, part of the JFC(Java Foundation Classes). It creates and manages tables in a GUI(graphical user interface) application.

Syntax

void setShowGrid(boolean showGrid)

Parameter

showGrid: A boolean that determines grid line visibility for both horizontal and vertical lines is true otherwise false.

Return Value

It does not have any return value.

Example

The following is an example to display both horizontal and vertical grid lines in a JTable ?

In this example, we create a Swing application that displays student marks in a table. It sets the font, row height, and grid color of the table, then adds the table to a scroll pane inside a JFrame, making it visible on the screen.

package my;
import java.awt.Color;
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
public class SwingDemo {
   public static void main(String[] argv) throws Exception {
      Integer[][] marks = {
         { 70, 66, 76, 89, 67, 98 },
         { 67, 89, 64, 78, 59, 78 },
         { 68, 87, 71, 65, 87, 86 },
         { 80, 56, 89, 98, 59, 56 },
         { 75, 95, 90, 73, 57, 79 },
         { 69, 49, 56, 78, 76, 77 }
      };
      String students[] = { "S1", "S2", "S3", "S4", "S5", "S6"};
      JTable table = new JTable(marks, students);
      Font font = new Font("Verdana", Font.PLAIN, 12);
      table.setFont(font);
      table.setRowHeight(30); table.setGridColor(Color.yellow);
      table.setShowGrid(true);
      JFrame frame = new JFrame();
      frame.setSize(600, 400);
      frame.add(new JScrollPane(table));
      frame.setVisible(true);
   }
}

Output

The above program produce the following result ?

Revathi Satya Kondra
Revathi Satya Kondra

Technical Content Writer, Tutorialspoint

Updated on: 2025-01-14T03:33:47+05:30

309 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements