您真正想要做的是传递mydialog给一个方法,该方法将找到其中包含的所有 JButton。这是一种方法,如果您传入 a Container( JDialogis a Container) 和 a List,它将List用所有的JButtonscontains填充,JDialog无论您如何添加JButtons.
private void getJButtons(Container container, List<JButton> buttons) {
if (container instanceof JButton) {
buttons.add((JButton) container);
} else {
for (Component component: container.getComponents()) {
if (component instanceof Container) {
getJButtons((Container) component, buttons);
}
}
}
}
基本上,此方法查看Container传入的是否为JButton. 如果是,则将其添加到List. 如果不是,那么它会查看 Container 的所有子Container节点并递归调用getJButtonsContainer。这将搜索整个 UI 组件树并用它找到的List所有内容填充。JButtons
这有点难看,必须创建一个List并将其传递给getButtons方法,所以我们将创建一个看起来更好的包装器方法
public List<JButton> getJButtons(Container container) {
List<JButton> buttons = new ArrayList<JButton>();
getJButtons(container, buttons);
return buttons;
}
这个方便的方法只是List为你创建你的,将它传递给我们的递归方法,然后返回List.
现在我们有了递归方法和便捷方法,我们可以调用便捷方法来获取所有JButtons 的列表。之后,我们只需遍历列表中的项目并调用getText()或您想要对按钮执行的任何其他操作:
for (JButton button: getJButtons(mydialog)) {
String text = button.getText();
...
}