在我的 customJFileChooser中,我想获得 Open 按钮,所以我使用以下代码:
private static JButton getOpenButton(Container c) {
  Validator.checkNull(c);
  int len = c.getComponentCount();
  JButton button = null;
  for (int index = 0; index < len; index++) {
    if (button != null) {
      break;
    }
    Component comp = c.getComponent(index);
    if (comp instanceof JButton) {
      JButton b = (JButton) comp;
      if ("Open".equals(b.getText())) {
        return b;
      }
    }
    else if (comp instanceof Container) {
      button = getOpenButton((Container) comp);
    }
  }
  return button;
}
这段代码的问题是它效率低下(因为递归)并且如果使用本地化也可能被破坏(因为“Open”这个词是硬编码的)。
我还想获得JTextField用户可以在其中输入文件的名称和路径的信息。我正在使用此代码来获取此组件:
private static JTextField getTextField(Container c) {
  Validator.checkNull(c);
  int len = c.getComponentCount();
  JTextField textField = null;
  for (int index = 0; index < len; index++) {
    if (textField != null) {
      break;
    }
    Component comp = c.getComponent(index);
    if (comp instanceof JTextField) {
      return (JTextField) comp;
    }
    else if (comp instanceof Container) {
      textField = getTextField((Container) comp);
    }
  }
  return textField;
}
有没有更好的方法可以获得打开按钮和JTextField?