Example 3
Home ] Up ] Example 1 ] Example 2 ] [ Example 3 ] Example 4 ] Example 5 ] Example 6 ]

 

 

Even now, the results doesn't look like much.  Everything is kind of scrunched together.

We can improve things by using struts, which can introduce vertical or horizontal space:

package swingExamples;

import java.awt.Container;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

class BoxLayoutExamplePanel extends JPanel
{
  public BoxLayoutExamplePanel()
  {
    setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
    add(new JButton("Click me"));
    add( Box.createVerticalStrut(10) );
    add(new JLabel("I am a label"));
    add( Box.createVerticalStrut(5) );
    JTextField textField = new JTextField("Text field", 20);
    textField.setMaximumSize(textField.getPreferredSize());
    add(textField);
    add( Box.createVerticalStrut(40) );
    add(new JButton("A very long button label is this..."));
  }
}

public class BoxLayoutExample3 extends JFrame
{
  public BoxLayoutExample3()
  {
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setTitle("BoxLayout");
    Container contentPane = getContentPane();
    contentPane.add(new BoxLayoutExamplePanel());
  }
  
  public static void main(String[] args)
  {
    JFrame frame = new BoxLayoutExample3();
    frame.setSize(300, 200);
    frame.setVisible(true);
  }
}

which produces:

As you can see, the struts have introduced some vertical spacing between the components.

 

This page was last modified on 02 October, 2007