展开全部
JTabel是Swing里的表格组件,它的行选取事件, 不是由JTabel直接接受的,而是通过给SelectionModel 添加ListSelectionListener 来对选取事件作出反应62616964757a686964616fe59b9ee7ad9431333366306533.jtable.getSelectionModel().addListSelectionListener(....)
支持单选, 多选, 鼠标上下移动选择等, 完整的表格选取参考代码如下import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class TableDemo extends JFrame {
String[] names = { "姓名", "等级" };// 表格标题
String[][] data = { { "张三", "A" }, { "李四", "B" }, { "王五", "C" } };//表格数据
public TableDemo() {
JTable table = new JTable(data, names);
JScrollPane jsp = new JScrollPane(table);
add(jsp);
setSize(300, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
// 先获取SelectionModel ,然后添加事件响应器
table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
if (!e.getValueIsAdjusting()) {
//支持拖动多选
int[] rows = table.getSelectedRows();
// int[] cols = table.getSelectedColumns();//选中的列
for (int i : rows) {
System.out.println("#方法一:\t" + table.getValueAt(i, 0) + "\t" + table.getValueAt(i, 1));
}
//支持单选
// int row=table.getSelectedRow();//选中行
// //int col=table.getSelectedColumn();//选中列
// System.out.println("方法一:"+table.getValueAt(row, 0)+"\t"+table.getValueAt(row, 1));
}
}
});
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
new TableDemo().setVisible(true);//窗口可见
}
});
}
}