本篇說明 JUCE 的另一個排版工具——juce::FlexBox。
juce::Flexbox 的設計構想來自於 CSS 中的 Flexbox,透過預先定義的版面規則來安排 GUI Controls 的位置與大小,用於複雜的 GUI Layout 比手工打造來得省力,有時候也更好維護。
修改前幾篇使用的範例,三個按鈕改用 juce::FlexBox 定位,程式碼修改如下:
void MainComponent::resized()
{
  const int kRowDistance = 10;
  const int kButtonDistance = 20;
  auto bounds = getLocalBounds().reduced(20, 10);
  auto first_row = bounds.removeFromTop(getLocalBounds().getHeight() * 0.2);
  // Caculate width for each button.
  const auto button_width = (bounds.getWidth() - (kButtonDistance * 2.0)) / 3.0;
  const auto button_height= getLocalBounds().getHeight() * 0.2;
  juce::FlexBox fb;
  fb.flexWrap		= juce::FlexBox::Wrap::noWrap;
  fb.justifyContent	= juce::FlexBox::JustifyContent::spaceBetween;
  fb.alignContent	= juce::FlexBox::AlignContent::center;
  
  fb.items.add(juce::FlexItem(google_button_).withMinWidth(button_width).withMinHeight(button_height));
  fb.items.add(juce::FlexItem(duckduckgo_button_).withMinWidth(button_width).withMinHeight(button_height));
  fb.items.add(juce::FlexItem(bing_button_).withMinWidth(button_width).withMinHeight(button_height));
  
  auto first_row = bounds.removeFromTop(getLocalBounds().getHeight() * 0.2);
  fb.performLayout(first_row);
}
利用 getLocalBounds 函數取得 MainComponent 的可用大小,等邏輯維持不變。接著計算按鈕的寬以及高。
建立一個 juce::FlexBox 物件,並設定其屬性:
完成屬性設定後,再將按鈕,以 FlexItem 包裝後,加到 FlexBox 物件內,並給定想要的大小值。範例中使用 withMinWidth, withMinHeight 是定義最小值。
最後呼叫 FlexBox::performLayout 函數,並提供作用範圍,即完成三個按鈕的排版。效果如下:
