jtable行的动态(实际)上下文菜单

时间:2016-09-27 08:12:21

标签: java swing jtable jpopupmenu

我想在上下文菜单中使用不同的菜单项,具体取决于我在JTable中单击的行

大多数示例并未真正显示上下文菜单(应根据上下文填充 - 所选行)

我试过了:

    popupMenu = new JPopupMenu(){
         @Override
        public void show(Component invoker, int x, int y) {
            int rowAtPoint = table.rowAtPoint(SwingUtilities.convertPoint(this, new Point(x, y), table));
                FilesManager.this.generateTablePopupMenu(rowAtPoint);
            super.show(invoker, x, y);
        }
    };

其中generateTablePopupMenu根据行数据添加/删除menuitems

但它不起作用,索引(rowAtPoint)不返回正确的值

1 个答案:

答案 0 :(得分:2)

JPopupMenu#show(int, int) (Java Platform SE 8)

  

public void show(Component invoker,int x,int y)

     

在组件调用程序的坐标空间中的x,y位置显示弹出菜单      

<强>参数:

     
      
  • invoker - 弹出菜单出现在其空间中的组件
  •   
  • x - 调制程序的坐标空间中要显示弹出菜单的x坐标
  •   
  • y - 调用者显示弹出菜单的坐标空间中的y坐标
  •   

因此,没有必要使用SwingUtilities.convertPoint(...)方法转换坐标。

import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;

public class JTablePopupMenuTest {
  public JComponent makeUI() {
    JTable table = new JTable(new DefaultTableModel(5, 3));
    table.setFillsViewportHeight(true);
    JPopupMenu popupMenu = new JPopupMenu() {
      @Override
      public void show(Component invoker, int x, int y) {
        //int rowAtPoint = table.rowAtPoint(
        //    SwingUtilities.convertPoint(this, new Point(x, y), table));
        //FilesManager.this.generateTablePopupMenu(rowAtPoint);
        int rowAtPoint = table.rowAtPoint(new Point(x, y));
        System.out.println(rowAtPoint);
        super.show(invoker, x, y);
      }
    };
    table.setComponentPopupMenu(popupMenu);

    JPanel p = new JPanel(new BorderLayout());
    p.add(new JScrollPane(table));
    return p;
  }
  public static void main(String... args) {
    EventQueue.invokeLater(() -> {
      JFrame f = new JFrame();
      f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
      f.getContentPane().add(new JTablePopupMenuTest().makeUI());
      f.setSize(320, 240);
      f.setLocationRelativeTo(null);
      f.setVisible(true);
    });
  }
}