1

私のカスタムJFileChooserでは、[開く]ボタンを取得したいので、次のコードを使用しています。

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;
}

このコードの問題は、(再帰のために)非効率的であり、ローカリゼーションを使用すると(「開く」という単語がハードコーディングされているため)壊れることもあるということです。

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か?

4

1 に答える 1

1

カスタムファイルチューザーのコンストラクターで、setApproveButtonTextメソッドを呼び出し、[開く]ボタンに使用するカスタム文字列を渡しました。以下のメソッドを使用して[開く]ボタンを取得する前に、このメソッドを呼び出しましたgetOpenButton。このようにして、JVMが使用しているロケールに関係なく、すべてのOSプラットフォームで[開く]ボタンが表示されることが保証されます。

private final String title;

public CustomFileChooser(String title) {
  this.title = title;
  setApproveButtonText(title);
  this.button = getOpenButton(this);
}

private 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 (this.title.equals(b.getText())) {
        return b;
      }
    }
    else if (comp instanceof Container) {
      button = getOpenButton((Container) comp);
    }
  }
  return button;
}
于 2013-01-11T20:51:34.763 に答える