Creating GUI components involves several steps. We will illustrate these with buttons, which are represented in Swing by the JButton class:
Look at the code in class ButtonDemo on-line, which has an inner class to listen to both buttons. Then look at the better button demo where each class has a separate listener.
A JFrame can also be assigned this layout manager by executing:
setLayout(new FlowLayout());
BorderLayout has two constructors:
public BorderLayout() public BorderLayout(int horizGap, int vertGap) // leaves given gaps between components.
The layout manager of an applet or panel can be changed to BorderLayout by executing:
setLayout(new BorderLayout())
Components are added by using a more refined version of add:
add(component, direction)
Thus to add a button on the north, write
add(startButton, BorderLayout.NORTH)
Components added to "North" and "South" extend to the left and right edges of the Applet, while those added "East" and "West" extend up and down to the components to the "North" and "South". The component in the "Center" fills the remaining space.
If one component is omitted, other components stretch to fill that space.
With the BorderLayout, components stretch to fill all of the container. As a result using border layout by itself can often make layouts look distorted.
public GridLayout(int rows, int cols) // Construct layout w/ given rows and columns public GridLayout(int rows, int cols, int h, int v) // Construct layout w/ given rows and columns, and // horiz and vertical gaps of h and v between components
Executing
setLayout(new GridLayout(2,3))
divides the applet into 2 rows and 3 columns. When "add" method is executed, components are added from left to right first across the first row, then second row, etc.
The only somewhat unfortunate thing about GridLayout is that all components added are resized to be exactly the same size. See GridTest for an example where buttons all the same.
The constructor for a panel is:
public JPanel()Again, see GridTest for an example of using a panel
See the calculator program for another relatively complex example of laying out buttons and a label.