import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; import javax.swing.table.*; public class JTableTest extends JFrame implements TableColumnModelListener, TableModelListener { JTable jt; public JTableTest() { super("JTable Test"); //Create the table and give the data as a two-dimensional //String array and the column headers as a one-dimensional String array. jt = new JTable(new String[][] { {"This", "is", "cell 13"}, {"a", "Test", "cell 23" }, {"cell 31", "cell 32", "cell 33" } }, new String[] {"Col 1", "Col 2", "Col 3"}); //Listen for events from the column model. jt.getColumnModel().addColumnModelListener(this); //Listen for events from the tabel model. jt.getModel().addTableModelListener(this); //Increase the distance between the cells. jt.setIntercellSpacing(new Dimension(15, 15)); //Use cell selections instead of row selections. Note that we can //still select ranges of cells, like we could select ranges //of rows before. jt.setCellSelectionEnabled(true); jt.setRowSelectionAllowed(false); //Cell editing will start when the user clicks this button. JButton b = new JButton("Edit"); b.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //Start editing the cell at row 2, column 2. jt.editCellAt(2, 2); //Give focus to the table. If the button keeps focus //the cell can not be edited. jt.requestFocus(); } }); getContentPane().add(b, BorderLayout.NORTH); //Place the table in a JScrollPane and display it. JScrollPane jsp = new JScrollPane(jt); getContentPane().add(jsp, BorderLayout.CENTER); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { e.getWindow().dispose(); System.exit(0); } }); setSize(300, 200); setVisible(true); } public void columnAdded(TableColumnModelEvent e) { System.out.println("column added"); } public void columnMarginChanged(ChangeEvent e) { System.out.println("column margin changed"); } public void columnMoved(TableColumnModelEvent e) { System.out.println("column moved"); } public void columnRemoved(TableColumnModelEvent e) { System.out.println("column removed"); } public void columnSelectionChanged(ListSelectionEvent e) { System.out.println("selection: " + e.getFirstIndex() + " - " + e.getLastIndex() + " valueIsAdjusting: " + e.getValueIsAdjusting()); int[] sel = jt.getColumnModel().getSelectedColumns(); for (int i = 0; i < sel.length; i++) System.out.println("column " + sel[i] + " selected"); sel = jt.getSelectedRows(); for (int i = 0; i < sel.length; i++) System.out.println("row " + sel[i] + " selected"); System.out.println(); } public void tableChanged(TableModelEvent e) { System.out.println("table changed "); } public static void main(String args[]) { new JTableTest(); } }