gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 03:20:14 30 4
gpt4 key购买 nike

我想要上下文菜单中的不同菜单项,具体取决于我在 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/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com