我有一个包含许多文本字段和其他控件的锚点窗格。我想获取所有控件及其名称和id的值。
例如:如何清除所有文本字段值?
答案 0 :(得分:7)
直截了当的解决方案是遍历AnchorPane的所有子项并寻找TextFields:
for (Node node : anchorPane.getChildren()) {
System.out.println("Id: " + node.getId());
if (node instanceof TextField) {
// clear
((TextField)node).setText("");
}
}
答案 1 :(得分:5)
如果您需要递归方式测试,
public class NodeUtils {
public static <T extends Pane> Map<Node, Object> formValues(T parent) {
return formValues(parent, new HashMap<>());
}
private static <T extends Pane> Map<Node, Object> formValues(T parent, Map<Node, Object> map) {
for (Node node : parent.getChildren()) {
// Nodes - You can add more.
if (node instanceof TextField) {
map.put(node, ((TextField) node).getText());
}
if (node instanceof PasswordField) {
map.put(node, ((PasswordField) node).getText());
}
if (node instanceof TextArea) {
map.put(node, ((TextArea) node).getText());
}
if (node instanceof CheckBox) {
map.put(node, ((CheckBox) node).isSelected());
}
// Recursive.
if (node instanceof Pane) {
formValues((Pane) node, map);
}
}
return map;
}
}
测试源,
Map<Node, Object> formValues = NodeUtils.formValues(source);
public class NodeUtils {
public static ArrayList<Node> getAllNodes(Parent root) {
ArrayList<Node> nodes = new ArrayList<>();
addAllDescendents(root, nodes);
return nodes;
}
private static void addAllDescendents(Parent parent, ArrayList<Node> nodes) {
// Get children.
List<Node> children = Collections.EMPTY_LIST;
if (parent instanceof ButtonBar) {
children = ((ButtonBar) parent).getButtons();
} else if (parent instanceof TabPane) {
for (Tab tab : ((TabPane) parent).getTabs()) {
Node tabContent = tab.getContent();
if (tabContent instanceof Parent) {
addAllDescendents((Parent) tab.getContent(), nodes);
} else {
// You can log and get a type that is not supported.
}
}
} else {
children = parent.getChildrenUnmodifiable();
}
// Add nodes.
for (Node node : children) {
nodes.add(node);
if (node instanceof Parent) {
addAllDescendents((Parent) node, nodes);
}
}
}
}
测试源,
List<Node> nodes = NodeUtils.getAllNodes(aPaneOrAnotherParentObject);
答案 2 :(得分:3)
这是一个Java 8版本:
if (AccessibilityManager.getInstance(context).isEnabled()) {
AccessibilityEvent event = AccessibilityEvent.obtain(
AccessibilityEvent.TYPE_ANNOUNCEMENT);
onInitializeAccessibilityEvent(event);
event.getText().add("some text");
event.setContentDescription(null);
yourContentView.requestSendAccessibilityEvent(this, event);
}