import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableModel;
public class JTableList extends JFrame {
JTable table;
TableModel model;
TableCellRenderer renderer;
JScrollPane scrollPane;
public JTableList() {
super("JTableList");
setDefaultCloseOperation(EXIT_ON_CLOSE);
String[] headers = { "A", "B", "C", "D", "E" };
String[][] data = { { "a1", "b1", "c1", "d1", "e1" },
{ "a2", "b2", "c2", "d2", "e2" },
{ "a3", "b3", "c3", "d3", "e3" },
{ "a4", "b4", "c4", "d4", "e4" },
{ "a5", "b5", "c5", "d5", "e5" } };
model = new DefaultTableModel(data, headers);
table = new JTable(model);
table.setEnabled(false);
table.setRowMargin(0);
table.getColumnModel().setColumnMargin(0);
table.setShowGrid(false);
table.addMouseMotionListener(new MouseMotionAdapter() {
public void mouseMoved(MouseEvent evt) {
int row = table.rowAtPoint(evt.getPoint());
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.setRowSelectionInterval(row, row);
}
});
table.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent evt) {
Point p = evt.getPoint();
int row = table.rowAtPoint(p);
int clm = table.columnAtPoint(p);
System.out.println(table.getValueAt(row, clm));
}
});
scrollPane = new JScrollPane(table);
scrollPane.setPreferredSize(table.getPreferredSize());
getContentPane().add(scrollPane);
pack();
setVisible(true);
}
public static void main(String[] args) {
new JTableList();
}
}