我有以下布局:



红色,蓝色和绿色部分是JPanel。在红色部分中,我有四个JLabel。现在,如果我调整JFrame的大小,标题标签将始终位于中间。但是我希望它们在红色部分中水平分布均匀。我应该使用哪种布局?

最佳答案

对顶部JPanel使用GridLayout(1,0)。这两个数字表示1行和可变列数。如果您使用的是JLabels,那么就足够了,特别是如果您将JLabels对齐常数设置为SwingConstants.CENTER。如果使用的是填充网格插槽的组件(例如JButtons),则可能需要使用GridLayout构造函数的其他变体,例如GridLayout(1,0,?,0)。是一个数字,告诉GridLayout插槽之间应有多少水平间距。

当然,整个GUI将使用BorderLayout。

有关更多和更好的信息,请查阅Lesson: Laying Out Components Within a ContainerA Visual Guide to Layout Managers

例如:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;

import javax.swing.*;

public class LayoutEg {

   private static void createAndShowGui() {
      String[] labelStrings = {"One", "Two", "Three", "Four"};
      JPanel topPanel = new JPanel(new GridLayout(1, 0));
      for (String labelString : labelStrings) {
         // create labels and center the text
         topPanel.add(new JLabel(labelString, SwingConstants.CENTER));
      }
      topPanel.setBackground(Color.red);

      JPanel centerPanel = new JPanel();
      centerPanel.setBackground(Color.blue);

      // setting preferred size for demonstration purposes only
      centerPanel.setPreferredSize(new Dimension(700, 400));

      JPanel bottomPanel = new JPanel();
      bottomPanel.setBackground(Color.green);

      // main panel uses BorderLayout
      JPanel mainPanel = new JPanel(new BorderLayout());
      mainPanel.add(centerPanel, BorderLayout.CENTER);
      mainPanel.add(topPanel, BorderLayout.PAGE_START);
      mainPanel.add(bottomPanel, BorderLayout.PAGE_END);


      JFrame frame = new JFrame("LayoutEg");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

10-07 18:57
查看更多