100 likes | 306 Views
Layout Mangers in Java. Tim McKenna Seneca@York. Layout Managers. A container (JPanel) has a layout manager. A layout manager is an object that manages the size and location of the components inside a container. Layout Managers.
E N D
Layout Mangers in Java Tim McKenna Seneca@York
Layout Managers • A container (JPanel) has a layout manager. • A layout manager is an object that manages the size and location of the components inside a container.
Layout Managers • A top-level container (JFrame) has a "content pane" which can be set to a container (JPanel). • This container can contain other containers. • Containers can be associated with different layout managers.
Containment Hierarchy • a logical hierarchy of containers • nest containers inside other containersJPanel (inside JPanel …) inside JFrame • advantages • a more organized, cleaner GUI layout • new components can be added to one container without affecting the other containers • programming technique: use of panels inside panels, each with different layouts
Use of Panels • Components are grouped into different containers, i.e. JPanels • Each container uses its own layout manager to position components. • Another container uses its layout manager to position the panels.
Three Common Layout Managers • java.awt.FlowLayout • java.awt.BorderLayout • java.awt.GridLayout
FlowLayout Manager • default for panels and applets • multiple components placed from left to right, from top to bottom • alignment and spacing can be adj. • Example: FlowLayoutManager.java • Exercise: Resize the window and see how the components flow.
BorderLayout Manager • default for JFrame window objects • locations marked by 5 areas: NORTH, SOUTH, EAST, WEST, CENTER • each area can contain only ONE object,usually a JPanel object • sizing of the areas: NORTH, SOUTH: horizontal expansion EAST, WEST: vertical expansion CENTER: flows • Example: BorderLayoutManager.java
GridLayout Manager • locations: a grid of rows and columns • size of the components: equal size • Example: GridLayoutManager.java
Layout Managers • Flow/Border/Grid Layouts all have limited use. • GridBagLayout is much more flexible and much harder to use. • bobjects package JPanelGrid combines GridLayout ease of use and GridBagLayout power. • see JFrameJPanelGrid.java