So that we can provide more space for the second panel, we will begin exploring the use ofLayout Managers
and the nesting of panels within panels.While objects can be placed at specific locations on the screen, as we have been doing all along with the drawing methods, you can see that this is quite laborious. Think, also, what would be involved if we were to resize the display and want to move things around to fill a smaller or larger display area.
Java provides help with the task of laying out components within a display area through a set of
Layout
managers. It currently provides five. In this step, we use two:FlowLayout
andBorderLayout
.Example Applet
import java.applet.Applet; import java.awt.*; public class step5 extends Applet{ // since step 4 didn't work, step 5 creates a nested framework for // components and a separate drawing area TextArea ta = new TextArea ("My Text Area", 5, 40); Button button = new Button ("Button"); Panel drawPanel = new Panel (); Panel topPanel = new Panel ( ); public void init ( ){ setBackground (Color.white); setForeground (Color.red); topPanel.add (ta); topPanel.add (button); drawPanel.setBackground (Color.blue); setLayout (new BorderLayout ( ) ); add ("North", topPanel); add ("Center", drawPanel); } // end init }// end step5Run the applet
Discussion
Two panels are created:
drawPanel
andtopPanel
. The former is used for drawing and the latter for holding the UI components. When the two components are added totopPanel
, theFlowLayout
is used since it is the default for Panels (actually, forContainers
).However, for the applet, the
BorderLayout
manager is used. Consequently, when we add the two panels to it, we must specify their relative positions to one another (i.e., North and Center).This produces a reasonable organization of panels, but how can we draw on the second panel (
drawPanel
)?