使用来自另一个方法的数组元素

Use array elements from another method

我对使用数组有疑问 我有一个为 JPanel 创建 JButton 的方法。我使用 JButton[] 在其中存储 7 个按钮。

问题是这些按钮最初必须设置为 setEnable(false)。它们仅在单击 openButton 时启用。

我想创建另一种方法,它只从 JButton[] 中获取所有元素并将它们设置为启用。我怎样才能做到这一点?

private JButton filterButtons() {
    //set layout for buttons
    setLayout(new BorderLayout());

    //Array to store description of buttons
    final String[] filterNames = {myEdgeDetect.getDescription(), 
                                    myEdgeHighlight.getDescription(),
                                    myFlipHorizontal.getDescription(),
                                    myFlipVeritcal.getDescription(),
                                    myGrayscale.getDescription(),
                                    mySharpen.getDescription(),
                                    mySoften.getDescription()};

    final JButton[] filterButtons = new JButton[filterNames.length];

    //This panel store buttons on north
    final JPanel buttonPanel = new JPanel();

    //Start to print buttons
    for (int i = 0; i < filterNames.length; i++) {
        filterButtons[i] = new JButton(filterNames[i]);
        filterButtons[i].setEnabled(false);
        filterButtons[i].addActionListener(null);
        filterButtons[i].setActionCommand(" " + i);
        buttonPanel.add(filterButtons[i]);

    }

如果您不是在方法中定义 filterNames 和 filterButtons,而是将它们设为 class 的字段,那么编写第二个遍历 filterButtons 并启用它们的方法将很容易。

Class Whatever {
    String[] filterNames;
    JButton[] filterButtons;

    private JButton filterButtons() {
      //set layout for buttons
      setLayout(new BorderLayout());

      //Array to store description of buttons
      filterNames = {myEdgeDetect.getDescription(), 
                                    myEdgeHighlight.getDescription(),
                                    myFlipHorizontal.getDescription(),
                                    myFlipVeritcal.getDescription(),
                                    myGrayscale.getDescription(),
                                    mySharpen.getDescription(),
                                    mySoften.getDescription()};

      filterButtons = new JButton[filterNames.length];

      //This panel store buttons on north
      final JPanel buttonPanel = new JPanel();

      //Start to print buttons
      for (int i = 0; i < filterNames.length; i++) {
        filterButtons[i] = new JButton(filterNames[i]);
        filterButtons[i].setEnabled(false);
        filterButtons[i].addActionListener(null);
        filterButtons[i].setActionCommand(" " + i);
        buttonPanel.add(filterButtons[i]);

      }
   }

   void enableButtons() {
    for (int i = 0; i < filterButtons.length; i++) {
        filterButtons[i].setEnabled(true);
    }
  }
}