java table右键点击事件

  表格监听步骤
  1 给表格 添加监听addMouseListener
  2 使用MouseAdapter类的mouseClicked方法

  3 通过MouseEvent类对象的getbutton方法来判断鼠标操作 BUTTON1 为左键  BUTTON3 为右键

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Vector;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
public class TableSj extends JFrame{
	JTable table;
	DefaultTableModel tableM;
	JScrollPane jsp;
	JPopupMenu jpm;
	Vector name = new Vector();
	Vector data = new Vector();
	
	public static void main(String[] args) {
		// TODO 自动生成的方法存根
		new TableSj();
	}
	TableSj(){
		name.add("姓名");
		name.add("年龄");
		data.add("张三");
		data.add("19");
		tableM = new DefaultTableModel(name,0);
		tableM.addRow(data);
		tableM.addRow(data);
		table = new JTable(tableM);
		jsp = new JScrollPane(table);
		
		table.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e){
				if (e.getButton() == MouseEvent.BUTTON3){
					//在table显示
					jpm = new JPopupMenu();
					
					//表格 的rowAtPoint方法返回坐标所在的行号,参数为坐标类型,
					int i = table.rowAtPoint(e.getPoint());
					
					jpm.add(i+"");
					jpm.show(table, e.getX(), e.getY());
				}
			}
		});
		this.add(jsp);
		this.setVisible(true);
		this.setSize(400, 400);
		this.setDefaultCloseOperation(EXIT_ON_CLOSE);
	}
}


你可能感兴趣的:(java table右键点击事件)