Categories
java layout-manager swing whitespace

Providing white space in a Swing GUI

170

A GUI with no white space appears ‘crowded’. How can I provide white space without resorting to explicitly setting the position or size of components?­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­

2

65

There are a number of ways in a Swing GUI to provide a separation between components, and white space around components:

But more generally, look to:

  • The spacing as can be defined in the layout constructors.
  • Borders.

Here is an example of using the layout separator hGap & vGap values & borders (specifically an EmptyBorder) to provide ‘white’ (actually shown as red to make it very obvious) space. Adjust the spinners to see the result.

With no GUI white space

With GUI white space

import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.event.*;

public class WhiteSpace {

    private JPanel gui = null;
    private BorderLayout mainLayout = 
        new BorderLayout(0, 0);
    private final FlowLayout buttonLayout = 
            new FlowLayout(FlowLayout.CENTER, 0, 0);
    private final JPanel buttonPanel = new JPanel(buttonLayout);
    private final SpinnerNumberModel hModel = 
            new SpinnerNumberModel(0, 0, 15, 1);
    private final SpinnerNumberModel vModel = 
            new SpinnerNumberModel(0, 0, 15, 1);
    private final SpinnerNumberModel hBorderModel = 
            new SpinnerNumberModel(0, 0, 15, 1);
    private final SpinnerNumberModel vBorderModel = 
            new SpinnerNumberModel(0, 0, 15, 1);
    private ChangeListener changeListener;

    public Container getGui() {
        if (gui == null) {
            gui = new JPanel(mainLayout);
            gui.setBackground(Color.RED);

            JTree tree = new JTree();
            tree.setVisibleRowCount(10);
            for (int ii = tree.getRowCount(); ii > -1; ii--) {
                tree.expandRow(ii);
            }
            gui.add(new JScrollPane(
                    tree,
                    JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                    JScrollPane.HORIZONTAL_SCROLLBAR_NEVER),
                    BorderLayout.LINE_START);
            gui.add(new JScrollPane(new JTextArea(10, 30)));

            gui.add(buttonPanel, BorderLayout.PAGE_START);

            changeListener = (ChangeEvent e) -> {
                int hGap = hModel.getNumber().intValue();
                int vGap = vModel.getNumber().intValue();
                int hBorder = hBorderModel.getNumber().intValue();
                int vBorder = vBorderModel.getNumber().intValue();
                adjustWhiteSpace(hGap, vGap, hBorder, vBorder);
            };

            addModel("H Gap", hModel);
            addModel("V Gap", vModel);
            addModel("H Border", hBorderModel);
            addModel("V Border", vBorderModel);
        }

        return gui;
    }

    private void addModel(String label, SpinnerNumberModel model) {
        buttonPanel.add(new JLabel(label));
        final JSpinner spinner = new JSpinner(model);
        spinner.addChangeListener(changeListener);
        buttonPanel.add(spinner);
    }

    private void adjustWhiteSpace(
            int hGap, int vGap, int hBorder, int vBorder) {
        mainLayout.setHgap(hGap);
        mainLayout.setVgap(vGap);
        buttonLayout.setHgap(hGap);
        gui.setBorder(new EmptyBorder
                (vBorder, hBorder, vBorder, hBorder));
        Container c = gui.getTopLevelAncestor();
        if (c instanceof Window) {
            Window w = (Window) c;
            w.pack();
        }
    }

    public static void main(String[] args) {
        Runnable r = () -> {
            WhiteSpace ws = new WhiteSpace();
            Container gui1 = ws.getGui();
            JFrame f = new JFrame("White (OK Red) Space");
            f.add(gui1);
            f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            f.setLocationByPlatform(true);
            f.setResizable(false);
            f.pack();
            f.setVisible(true);
        };
        SwingUtilities.invokeLater(r);
    }
}

0

    65

    There are a number of ways in a Swing GUI to provide a separation between components, and white space around components:

    But more generally, look to:

    • The spacing as can be defined in the layout constructors.
    • Borders.

    Here is an example of using the layout separator hGap & vGap values & borders (specifically an EmptyBorder) to provide ‘white’ (actually shown as red to make it very obvious) space. Adjust the spinners to see the result.

    With no GUI white space

    With GUI white space

    import java.awt.*;
    import javax.swing.*;
    import javax.swing.border.EmptyBorder;
    import javax.swing.event.*;
    
    public class WhiteSpace {
    
        private JPanel gui = null;
        private BorderLayout mainLayout = 
            new BorderLayout(0, 0);
        private final FlowLayout buttonLayout = 
                new FlowLayout(FlowLayout.CENTER, 0, 0);
        private final JPanel buttonPanel = new JPanel(buttonLayout);
        private final SpinnerNumberModel hModel = 
                new SpinnerNumberModel(0, 0, 15, 1);
        private final SpinnerNumberModel vModel = 
                new SpinnerNumberModel(0, 0, 15, 1);
        private final SpinnerNumberModel hBorderModel = 
                new SpinnerNumberModel(0, 0, 15, 1);
        private final SpinnerNumberModel vBorderModel = 
                new SpinnerNumberModel(0, 0, 15, 1);
        private ChangeListener changeListener;
    
        public Container getGui() {
            if (gui == null) {
                gui = new JPanel(mainLayout);
                gui.setBackground(Color.RED);
    
                JTree tree = new JTree();
                tree.setVisibleRowCount(10);
                for (int ii = tree.getRowCount(); ii > -1; ii--) {
                    tree.expandRow(ii);
                }
                gui.add(new JScrollPane(
                        tree,
                        JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                        JScrollPane.HORIZONTAL_SCROLLBAR_NEVER),
                        BorderLayout.LINE_START);
                gui.add(new JScrollPane(new JTextArea(10, 30)));
    
                gui.add(buttonPanel, BorderLayout.PAGE_START);
    
                changeListener = (ChangeEvent e) -> {
                    int hGap = hModel.getNumber().intValue();
                    int vGap = vModel.getNumber().intValue();
                    int hBorder = hBorderModel.getNumber().intValue();
                    int vBorder = vBorderModel.getNumber().intValue();
                    adjustWhiteSpace(hGap, vGap, hBorder, vBorder);
                };
    
                addModel("H Gap", hModel);
                addModel("V Gap", vModel);
                addModel("H Border", hBorderModel);
                addModel("V Border", vBorderModel);
            }
    
            return gui;
        }
    
        private void addModel(String label, SpinnerNumberModel model) {
            buttonPanel.add(new JLabel(label));
            final JSpinner spinner = new JSpinner(model);
            spinner.addChangeListener(changeListener);
            buttonPanel.add(spinner);
        }
    
        private void adjustWhiteSpace(
                int hGap, int vGap, int hBorder, int vBorder) {
            mainLayout.setHgap(hGap);
            mainLayout.setVgap(vGap);
            buttonLayout.setHgap(hGap);
            gui.setBorder(new EmptyBorder
                    (vBorder, hBorder, vBorder, hBorder));
            Container c = gui.getTopLevelAncestor();
            if (c instanceof Window) {
                Window w = (Window) c;
                w.pack();
            }
        }
    
        public static void main(String[] args) {
            Runnable r = () -> {
                WhiteSpace ws = new WhiteSpace();
                Container gui1 = ws.getGui();
                JFrame f = new JFrame("White (OK Red) Space");
                f.add(gui1);
                f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                f.setLocationByPlatform(true);
                f.setResizable(false);
                f.pack();
                f.setVisible(true);
            };
            SwingUtilities.invokeLater(r);
        }
    }
    

    0

      24

      When you use BoxLayout, Box.createVerticalGlue() method can help you to make some white space.

      Another method is BorderFactory.createEmptyBorder(int top, int left, int bottom, int right). It can help you to make some white space around component.

      Thanks for Andrew Thompson’s remind.I’ve revised BoxLayout in recent days and I find that Box.createVerticalGlue() can add some white space depend on the panel’s size and you can not set the explicit pixel value of the length of white space.But Box.createVerticalStrut() can do that. Here is a MCTaRE and show the effect of those two methods.

      enter image description here

      import java.awt.*;
      import java.awt.event.*;
      import javax.swing.*;
      import javax.swing.border.*;
      import javax.swing.event.*;
      
      public class WhiteSpace extends JFrame{
          static WhiteSpace whiteSpace;
          DemoPanel demoPanel;
          boolean withGlue;
          JSpinner spinner;
      
          public WhiteSpace(){
              initialWindow();
              demoPanel = new DemoPanel();
              ActionPanel actionPanel = new ActionPanel();
      
              setLayout(new BorderLayout());
      
              getContentPane().add(actionPanel,BorderLayout.NORTH);
              getContentPane().add(demoPanel,BorderLayout.CENTER);
                  setVisible(true);
          }
      
          public void initialWindow(){
              setSize(220, 300);
              setTitle("White Space");
              setResizable(false);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              setLocationRelativeTo(null);
              //Show the window in the middle of the screen
          }
      
          /**
           * @param args
           */
          public static void main(String[] args) {
              Runnable runnable = new Runnable() {
                  @Override
                  public void run() {
                      whiteSpace = new WhiteSpace();
                  }
              };
              SwingUtilities.invokeLater(runnable);
          }
      
          class DemoPanel extends JPanel{
              //Show the vertical white space between label1 and label2
              JLabel label1;
              JLabel label2;
              public void initialDemoPanel(){
                  setBorder(BorderFactory.createTitledBorder(getBorder(), "DemoPanel", TitledBorder.LEADING, TitledBorder.TOP, new Font("Default",Font.PLAIN,10), Color.gray));
                  setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
      
                  label1 = new JLabel("This is first line");
                  label2 = new JLabel("This is second line");
              }
      
              public DemoPanel(){
                  initialDemoPanel();
                  add(label1);
                  if(withGlue){
                      add(Box.createVerticalGlue());
                  }
                  add(label2);
              }
      
              public DemoPanel(int strutValue){
                  initialDemoPanel();
                  add(label1);
                  add(Box.createVerticalStrut(strutValue));
                  add(label2);
              }
          }
      
          class ActionPanel extends JPanel{
              public ActionPanel(){
                  setBorder(BorderFactory.createTitledBorder(getBorder(), "ActionPanel", TitledBorder.LEADING, TitledBorder.TOP, new Font("Default",Font.PLAIN,10), Color.gray));
      
                  setLayout(new BoxLayout(this,BoxLayout.X_AXIS));
                  JRadioButton glueButton = new JRadioButton("With Glue");
                  glueButton.addActionListener(new glueButtonListener());
                  add(glueButton);
      
                  add(Box.createHorizontalStrut(10));
                  //To create horizontal white space
                  JLabel strutLabel = new JLabel("Strut Value");
                  add(strutLabel);
                  spinner = new JSpinner(new SpinnerNumberModel(0,0,50,1));
                  spinner.addChangeListener(new spinnerListener());
                  add(spinner);
                  //public SpinnerNumberModel(Number value,Comparable minimum,Comparable maximum,Number stepSize)
              }
          }
      
          class glueButtonListener implements ActionListener{
              @Override
              public void actionPerformed(ActionEvent e) {
                  spinner.setValue(new Integer(0));
                  withGlue = (withGlue == true ? false:true);
                  whiteSpace.getContentPane().remove(demoPanel);
                  demoPanel = new DemoPanel();
                  whiteSpace.getContentPane().add(demoPanel,BorderLayout.CENTER);
                  whiteSpace.getContentPane().validate();
              }
          }
      
          class spinnerListener implements ChangeListener{
      
              @Override
              public void stateChanged(ChangeEvent e) {
                  int strutValue = (Integer) spinner.getValue();
                  whiteSpace.getContentPane().remove(demoPanel);
                  demoPanel = new DemoPanel(strutValue);
                  whiteSpace.getContentPane().add(demoPanel,BorderLayout.CENTER);
                  whiteSpace.getContentPane().validate();
              }
          }
      }
      

      Box.createHorizontalGlue() and Box.createHorizontalStrut(int height) can be used too. Besides, Box.createRigidArea(Dimension d) has the ability too create white space too.

      0