The best and easiest solution to your problem would be if you could give the buttons distinct names.
Remember: the name
of a component is distinct from the text
it displays! Your buttons could all be showing "text" to the users, but still have names like "button1", "button2", "button3".
In this case you could write
frame.button(JButtonMatcher.withName("button1").withText("text").andShowing()).click();
The next possibility would be to give the panels containing the buttons distinct names, for example "panel1", "panel2", "panel3".
If you can implement this you could write
frame.panel("panel1").button(JButtonMatcher.withText("text").andShowing()).click();
The last and worst possibility would be to write your own GenericTypeMatcher
/ NamedComponentMatcherTemplate
that returns only the n
th button matching the given text.
PLEASE BEWARE:
- this is a desparate measure if all other approaches fail
- This will lead to fragile tests
- You don't want to do this unless there is absolute no other way!
With these warnings in place, this is code:
public class MyJButtonMatcher extends NamedComponentMatcherTemplate<JButton> {
private String text;
private int index;
public MyJButtonMatcher(String text, int index) {
super(JButton.class);
this.text = text;
this.index = index;
requireShowing(true);
}
@Override
protected boolean isMatching(JButton button) {
if (isNameMatching(button.getName()) && arePropertyValuesMatching(text, button.getText())) {
return index-- == 0;
} else {
return false;
}
}
}