MainClass.java Source code

Java tutorial

Introduction

Here is the source code for MainClass.java

Source

import java.awt.BorderLayout;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.TableColumnModelEvent;
import javax.swing.event.TableColumnModelListener;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;

public class MainClass {
    public static void main(String args[]) {
        Object rows[][] = { { "A", "a" }, { "B", "b" }, { "E", "e" } };
        Object headers[] = { "Upper", "Lower" };

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JTable table = new JTable(rows, headers);

        TableColumnModelListener tableColumnModelListener = new TableColumnModelListener() {
            public void columnAdded(TableColumnModelEvent e) {
                System.out.println("Added");
            }

            public void columnMarginChanged(ChangeEvent e) {
                System.out.println("Margin");
            }

            public void columnMoved(TableColumnModelEvent e) {
                System.out.println("Moved");
            }

            public void columnRemoved(TableColumnModelEvent e) {
                System.out.println("Removed");
            }

            public void columnSelectionChanged(ListSelectionEvent e) {
                System.out.println("Selection Changed");
            }
        };

        TableColumnModel columnModel = table.getColumnModel();
        columnModel.addColumnModelListener(tableColumnModelListener);

        columnModel.setColumnMargin(12);

        TableColumn column = new TableColumn(1);
        columnModel.addColumn(column);

        JScrollPane pane = new JScrollPane(table);
        frame.add(pane, BorderLayout.CENTER);
        frame.setSize(300, 150);
        frame.setVisible(true);
    }
}