14. 58. 20. 表格选择与监听事件 Table Selection Events and Listeners

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;


public class JTableListSelectionListener {

	public static void main(String[] args) {
		JFrame f = new JFrame("JTableListSelectionListener");
		f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		final JTable table;
		String[] columnTitles = {"A","B","C","D"};
		Object[][] rowData = {{ "11", "12", "13", "14" }, { "21", "22", "23", "24" },
				{ "31", "32", "33", "34" }, { "41", "42", "44", "44" } };
		table = new JTable(rowData,columnTitles);
		
		table.setCellSelectionEnabled(true);//设置此表是否允许同时存在行选择和列选择。
		//返回用来维持行选择状态的 ListSelectionModel。 
		//此接口表示任何组件的当前选择状态,该组件显示一个具有稳定索引的值列表。
		ListSelectionModel cellSelectionModel = table.getSelectionModel();
		//单选,只能选择一个单元格
		cellSelectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		
		cellSelectionModel.addListSelectionListener(new ListSelectionListener(){

			public void valueChanged(ListSelectionEvent e) {//单元格值变动事件
				String selectedData = null;
				int[] selectedRow = table.getSelectedRows();//被选择的行
				int[] selectedColumns = table.getSelectedColumns();//被选择的列
				
				for(int i = 0; i < selectedRow.length; i++){//循环取出
					for(int j = 0; j < selectedColumns.length; j++){
						selectedData = (String)table.getValueAt(selectedRow[i], selectedColumns[j]);
					}
				}
				System.out.println("选择的: " + selectedData);
			}
		});
		
		f.add(new JScrollPane(table));
		f.setSize(300,200);
		f.setVisible(true);
	}

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值