java - jtable 行的动态(真实)上下文菜单

标签 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根据行数据添加/删除菜单项

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

最佳答案

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

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

Displays the popup menu at the position x,y in the coordinate space of the component invoker.

Parameters:

  • invoker - the component in whose space the popup menu is to appear
  • x - the x coordinate in invoker's coordinate space at which the popup menu is to be displayed
  • y - the y coordinate in invoker's coordinate space at which the popup menu is to be displayed

因此,没有必要使用 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);
    });
  }
}

关于java - jtable 行的动态(真实)上下文菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39719466/

相关文章:

java - 将数据从 RecyclerView.Adapter 传递到 fragment onClick

java - 将警告从后端代码传递到 Java 中的 Swing UI 的正确方法?

java - 如何使用 Jcombo + 监听器

java - 从行中获取 id

java - 如何使 jtable 单元格监听另一个单元格的更改

java - FTDI D2xx android java 不读

java - Rivr VoiceXML for Java 中的 "Wait a second"消息

java - 如果我的 map 需要小而不是快,我应该使用 Map<K,V> 的哪个实现?

Java编程-错误跟踪

java - 如何在运行时在 JFrame 中添加 JTable?