Java a simple jtable example for display

‮i.www‬giftidea.com

Here is an example of how to create a simple JTable in Java for displaying data:

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;

public class SimpleJTableExample {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Simple JTable Example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // Create some sample data
        Object[][] data = {
                {"John", 25, "Male"},
                {"Sarah", 31, "Female"},
                {"William", 43, "Male"},
                {"Emily", 19, "Female"},
                {"Michael", 37, "Male"}
        };

        // Create a JTable with the data
        String[] columnNames = {"Name", "Age", "Gender"};
        JTable table = new JTable(data, columnNames);

        // Add the table to a scroll pane
        JScrollPane scrollPane = new JScrollPane(table);

        // Add the scroll pane to the frame
        frame.add(scrollPane);

        // Set the size of the frame and show it
        frame.pack();
        frame.setVisible(true);
    }
}

In this example, we create a JFrame and a JTable with sample data. The data is stored in a two-dimensional array, with each row representing a person and each column representing a different attribute (name, age, gender).

We then create a JTable instance by passing in the data and column names as arguments to its constructor. We also create a JScrollPane and add the JTable to it, so that the table is scrollable if there are too many rows to fit on the screen.

Finally, we add the JScrollPane to the JFrame and show it. When you run this example, you should see a window with a JTable that displays the sample data.

Note that this is a very basic example, and you can customize the appearance and behavior of the JTable in many ways. For example, you can use a custom TableModel to handle the data and customize the rendering of cells using renderers and editors.