[英]How to automatically right click on jtable and select first JMenu item
I have a swing application where we pass a json to the textfield and after clicking on load button, a table is getting populated.我有一个 swing 应用程序,我们将 json 传递给文本字段,单击加载按钮后,将填充一个表格。
I am able to load the json and selected the whole table automatically through following code:我能够加载 json 并通过以下代码自动选择整个表:
resourceButton.doClick();
this.table.selectAll();
Now I want to right click on the selected table and choose first option from the popupmenu.现在我想右键单击选定的表并从弹出菜单中选择第一个选项。 Any suggestions?
有什么建议么?
I want to automate this particular part of UI:我想自动化 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.
现在我想右键单击选定的表并从弹出菜单中选择第一个选项。
A popup menu contains JMenuItem
s or JMenu
s.弹出菜单包含
JMenuItem
或JMenu
。 Either way, the ones with an actual action are the JMenuItem
s.无论哪种方式,具有实际操作的都是
JMenuItem
。
A JMenuItem
is a button as well. JMenuItem
也是一个按钮。 You already use resourceButton.doClick()
.您已经使用了
resourceButton.doClick()
。 You can use doClick
to a JMenuItem
too.您也可以将
doClick
用于JMenuItem
。
An example:一个例子:
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);
});
}
}
You can use button for this purpose instead of the popup menu.您可以为此目的使用按钮而不是弹出菜单。 You can add the button and write an action listener on it like below
您可以添加按钮并在其上编写一个动作侦听器,如下所示
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);
}));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.