jtable 选中事件
时间: 2023-07-30 15:08:18 浏览: 178
js客户端对table表进行选中操作
在 Java Swing 中,可以通过添加 ListSelectionListener 监听器来监听 JTable 的选中事件。以下是一个简单的示例代码:
```java
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class JTableSelectionDemo extends JFrame {
private JTable table;
private JLabel label;
public JTableSelectionDemo() {
// 创建 JTable
String[] columnNames = {"姓名", "年龄", "性别"};
Object[][] rowData = {
{"张三", 25, "男"},
{"李四", 31, "女"},
{"王五", 28, "男"}
};
table = new JTable(rowData, columnNames);
// 创建标签
label = new JLabel("请选择一行");
// 添加选中监听器
table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
int row = table.getSelectedRow();
if (row >= 0) {
String name = (String) table.getValueAt(row, 0);
label.setText("你选中了 " + name);
}
}
});
// 添加组件
JScrollPane scrollPane = new JScrollPane(table);
add(scrollPane);
add(label, "South");
// 设置窗口属性
setTitle("JTable 选中事件示例");
setSize(300, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
new JTableSelectionDemo();
}
}
```
运行该示例代码,选中 JTable 中的某一行,即可在标签中显示选中行的姓名。
阅读全文