java实现table添加右键点击事件监听操作示例

时间:2021-12-23 14:14:45

本文实例讲述了java实现table添加右键点击事件监听操作。分享给大家供大家参考,具体如下:

表格监听步骤

1 给表格 添加监听addmouselistener

2 使用mouseadapter类的mouseclicked方法

3 通过mouseevent类对象的getbutton方法来判断鼠标操作 button1 为左键  button3 为右键

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
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<string> name = new vector<string>();
  vector<string> data = new vector<string>();
  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程序设计有所帮助。

原文链接:https://blog.csdn.net/qq_36238595/article/details/72809903