如何自动右键单击 jtable 和 select 第一个 JMenu 项

How to automatically right click on jtable and select first JMenu item

我有一个 swing 应用程序,我们将 json 传递给文本字段,在单击加载按钮后,table 被填充。

我可以通过以下代码自动加载 json 并选择整个 table:

  resourceButton.doClick();
  this.table.selectAll();

现在我想右键单击所选 table 并从弹出菜单中选择第一个选项。有什么建议吗?

我想自动执行 UI 的这个特定部分:


    JMenuItem addToSiteMap = new JMenuItem("Add to site map");
    addToSiteMap
        .addActionListener(e -> IntStream.of(tab.getTable().getSelectedRows()).forEach(row -> {
          int index = (int) tab.getTable()
              .getValueAt(row, tab.getTable().getColumn("#").getModelIndex());
          HttpRequestResponse httpRequestResponse = this.httpRequestResponses.get(index);
          callbacks.addToSiteMap(httpRequestResponse);
        }));

Now I want to right click on the selected table and choose first option from the popupmenu.

弹出菜单包含 JMenuItemJMenu。不管怎样,有实际行动的是JMenuItems.

A JMenuItem 也是一个按钮。您已经使用 resourceButton.doClick()。您也可以将 doClick 用于 JMenuItem

一个例子:

public class TableTest {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setLayout(new BorderLayout());

            JTable table = new JTable(new Object[][] { { "something" } }, new String[] { "column" });

            JPopupMenu popupMenu = new JPopupMenu();
            JMenuItem menuItem = new JMenuItem("MenuItem");
            menuItem.addActionListener(e -> {
                System.out.println("Popup item clicked.");
            });
            popupMenu.add(menuItem);

            table.setComponentPopupMenu(popupMenu);

            frame.add(new JScrollPane(table), BorderLayout.CENTER);

            JButton button = new JButton("Click me to fire Popupmenu item");
            button.addActionListener(e -> {
                menuItem.doClick();
            });
            frame.add(button, BorderLayout.PAGE_END);

            frame.pack();
            frame.setLocationByPlatform(true);
            frame.setVisible(true);
        });
    }
}

为此,您可以使用按钮代替弹出菜单。您可以添加按钮并在其上编写一个动作侦听器,如下所示

button.addActionListener(e -> IntStream.of(this.getTable().getSelectedRows()).forEach(row -> {
      int index = (int) this.getTable()
              .getValueAt(row, this.getTable().getColumn("#").getModelIndex());
      HttpRequestResponse httpRequestResponse = this.httpRequestResponses.get(index);
      resourceTextField.setText(String.valueOf(index));
  callbacks.addToSiteMap(httpRequestResponse);
    }));