Setting BoxLayout for a JFrame

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   go to next page

Answer:

FlowLayout and Boxlayout

Setting BoxLayout for a JFrame

Recall that to set the layout manager of a container to BoxLayout you need to include a reference to the container in the constructor:

BoxLayout(Container contain, int axis) 

    contain: the container this layout manager is for
            
    axis: BoxLayout.X_AXIS  — for left to right alignment
          BoxLayout.Y_AXIS  — for top to bottom alignment

A problem with doing this with a JFrame is that the container that holds the GUI components is the content pane of the frame. (JFrame are made up of several components, which you usually don't need to worry about.) To get a reference to the content pane use the getContentPane() method of the frame. Here is how you could change the layout manager of the frame of the previous example:

    setLayout( new BoxLayout( getContentPane(), BoxLayout.Y_AXIS ); 
    add( dataPanel );
    add( butPanel );

This would have no visible effect in the example program unless the size of the frame were made much wider. A wide frame using FlowLayout would arrange dataPanel and butPanel horizontally. A wide frame using BoxLayout would arrange dataPanel and butPanel vertically.

QUESTION 18:

Does programming a GUI involve some trial and error?