Layout Managers - PowerPoint PPT Presentation

1 / 37
About This Presentation
Title:

Layout Managers

Description:

... how to create a simple JFrame with nothing on it, and we learned how to create a ... For instance, say we create a frame, and set it's size to 500 by 500 (pixels) ... – PowerPoint PPT presentation

Number of Views:86
Avg rating:3.0/5.0
Slides: 38
Provided by: chrisf2
Category:
Tags: create | how | layout | managers | to

less

Transcript and Presenter's Notes

Title: Layout Managers


1
Layout Managers
  • In the previous lecture, we learned how to create
    a simple JFrame with nothing on it, and we
    learned how to create a JPanel and add it to this
    Frame, and we learn to add some simple JButtons
    (that currently do nothing) to this panel.
  • Great, we added them, but they show up
    horizontally on the screen. What if we wanted
    them vertical, or we wanted two on one row, and
    one of the bottom, or we wanted the Buttons to be
    different sizes.

2
Layout Managers
  • You get the point. We want to customize how
    things appear on the screen.
  • We can do with with a Layout Manager
  • Both JFrames and JPanels have LayoutManagers.
    When you create a new JFrame or JPanel, they are
    created with their default Layout Managers
    (JFrame defaults to a BorderLayout. JPanel
    defaults to a FlowLayout)

3
Layout Managers
  • Layout Managers are Javas flexible way of
    deciding how to determine what goes where on the
    screen, taking into account that different screen
    sizes might be being used be various users.
  • When you call the add() method of a Container, it
    is actually the Layout Manager which decides
    where to place the item.

4
Layout Managers
  • A note on Layout Managers, and something to watch
    out for. Layout Managers make a best-effort to
    accommodate the requests of all the possible.
  • For instance, say we create a frame, and set its
    size to 500 by 500 (pixels). Then we add two
    buttons to it, but on both JButtons we call
  • button1.setPreferredSize(new
    Dimension(500,500))
  • button2.setPreferredSize(new
    Dimension(500,500))

5
Layout Managers
  • Well, if this happens, one, or both, of these
    components are going to get the proverbial shaft,
    and not get what they want.
  • Unless you know Swing and the Java Graphics
    Libraries better than 95 of the Professional
    Java Developers out there, this is fairly
    non-deterministic (youre not going to know what
    is going to happen.)
  • The compiler also wont flag anything like this.
    Its all legal syntax.

6
Layout Managers
  • Moral of the lesson- When designing GUI pieces,
    make sure what you want can logically happen.
    This may seem obvious, but its frequently
    overlooked. If the Layout Manager isnt doing
    what you want, make sure what you want is
    actually possible.

7
Classes to familiarize yourself with
  • the Dimension class. Holds a Dimension (a width
    and a height) It takes two elements in the
    constructor for Width and Height (use ints!).
    Go look at its API page. Its a fairly simple
    class, but used a lot, so understand it.
  • Dimension someSizenew Dimension(400,300)
  • int widthsomeSize.getWidth() //sets width
    to 400
  • int heightsomeSize.getHeight() //sets height
    to 300

8
Point
  • Same concept as Dimension, just a holder class
    for a point (x,y) in coordinate space.
  • Constructor takes (x,y) as arguments, again, try
    to use ints for simplicity if your application
    allows.
  • Point locationnew Point(125,200)
  • int xCoordlocation.getX()
  • int yCoordlocation.getY()

9
Component Sizes
  • Another confusing thing is that, all components
    seem to have 4 different methods to specify their
    size.
  • setSize()
  • setPreferredSize()
  • setMinimumSize()
  • setMaximumSize()

10
Component Sizes
  • setSize is used with with absolute positioning,
    and most Layout Managers ignore this.
  • setPreferredSize is generally what you want to
    set.. you tell the Layout Manager how big you
    would like it to be, and it tries to accommodate
    the request.
  • setMinimumSize and setMaximumSize are self
    explanatory, and should only be used when there
    is a specific reason to doing so. Again, these
    are not absolute (they cant be).

11
Flow Layout
  • The JPanels default is a FlowLayout.
  • FlowLayouts arrange what you add to them from
    left to right, until it runs out of space. When
    it does, it starts a new row directly below the
    previous row and starts arrange left to right.
  • The components are arranged in a flow of left
    to right and top to bottom. If a user resizes
    the a FlowLayout container, FlowLayout reflows
    the components dynamically.

12
How to set a Layout Manager
  • Every Container (Frames, Panels, JDialogs) has a
    getLayout and setLayout methods.
  • You can set a new Layout Manager by using,
    obviously, setLayout
  • JPanel thisPanelnew JPanel()
  • FlowLayout fl new FlowLayout()
  • thisPanel.setLayout(fl)

13
Flow Layout
  • Ok, back to Flow Layout. By default, FlowLayout
    with center all the components on each row.
  • This, also, can be changed. Call FlowLayout with
    an argument specifying alignment.
  • JPanel examplePanelnew JPanel()
  • FlowLayout flnew FlowLayout(FlowLayout.LEFT)
  • examplePanel.setLayout(fl)
  • Now the components will be left aligned on each
    row.

14
BorderLayout
  • Another Layout Manager which is commonly used is
    the BorderLayout.
  • JFrames default Layout Manager is the
    BorderLayout.
  • BorderLayout differs from FlowLayout in that it
    lets you decide where in the Layout to place
    your item, unlike FlowLayout, where items are
    added left to right

15
BorderLayout
  • BorderLayout allows you to specify North, West,
    Center, East or South.
  • Only 1 component may be in each (you cant have 2
    Norths)

Center
North
West
East
South
16
BorderLayout
  • BorderLayout will actually expand each of its
    components to fill the available space, unlike
    FlowLayout, which will try to obey a components
    PreferredSize
  • If the container is resize, the outer edges are
    redrawn first, and then the center is recomputed
    and redraw.

17
BorderLayout
  • To add to a border layout, do the following
  • JPanel aPanelnew JPanel()
  • aPanel.setLayout(new BorderLayout())
  • aPanel.add(someComponent,BorderLayout.NORTH)
  • In your omit the 2nd argument, BorderLayout will
    add your component to the Center
  • Word of caution in your travels, you may see
    code that does
  • aPanel.add(someComponent,South)
  • This will actually work UNLESS you misspell
    or use the wrong case with South then, it
    will compile fine, but wont work right. Dont
    be lazy, use the class constant.

18
Layering Panels
  • Ok, good, BorderLayout lets us place things
    where we want. Ok. But how many things can we
    actually place?
  • To get around this, you have two choices
  • Use another, more complicated Layout Manager
    which gives you the ability to add a large amount
    of components
  • Layer Panels within other Panels to get your
    desired behavior.
  • There is no hard rule for this, but the general
    rule is, if youre just going to add a couple
    more components, (say, 6 or 7), go ahead an layer
    the two panels if youd like. If youre putting
    a LOT of GUI elements on the screen, pick another
    Layout Manager. Following layers and layers of
    JPanels is flaky, inefficient and hard to debug.

19
Layering Panels
  • JPanels are neat because we can use them as a
    component (we can add them to containers) and
    they are containers themselves. So, we can use
    this ability to do stuff like the Following.
  • JPanel p1new JPanel()
  • JPanel p2new JPanel()
  • p1.setLayout(newBorderLayout))
  • p2.setLayout(new BorderLayout())
  • p1.add(button1,BorderLayout.NORTH)
  • p1.add(button2,BorderLayout.EAST
  • p1.add(button3,BorderLayout.WEST)
  • p2.add(button4,BorderLayout.EAST)
  • p2.add(button5,BorderLayout.WEST)
  • p2.add(button6, BorderLayout.SOUTH)
  • p1.add(p1,BorderLayout.SOUTH) //we add the 2nd
    panel to the south area of the first
  • someFrame.getContentPane().add(p1) // now we
    have 4 rows of buttons, the middle two
  • // rows having two buttons in
    each rowfs

20
Grid Layout
  • the Grid Layout manager arranges the screen into
    a grid of equal sized rows and sizes.
  • Conceptually, this is layed out like an Microsoft
    Excel spreadsheet. When the Grid Layout is
    resized, the cells can grow and shrink, but they
    ALL grow and shrink, so they are all still the
    same size.

21
Grid Layout
  • To create GridLayout, we have a few constructors
    we can use.
  • somePanel.setLayout(new GridLayout(8,3)) // 8
    rows, 3 columns
  • -or-
  • somePanel.setLayout(new GridLayout(8,3,4,4))
  • The additional arguments are horizontal and
    vertical gaps, or spacing, between the cells.
    (these are in pixels)

22
Grid Layout
  • There are also methods you can call after the
    constructor to set these gaps.
  • GridLayout glnew GridLayout()
  • gl.setHGap(3)
  • gl.setVGap(5)

23
Grid Layout
  • Components are added to a grid layout in a
    sequentially, almost reminiscent of a FlowLayout.

  • The first add() method call adds the component to
    the 1st row and 1st column.
  • The second add() method call adds the component
    to the 1st row and 2nd column.
  • And so forth, until the 1st row is filled in,
    then the 2nd row begins with the 1st column, and
    so forth until the entire container is filled
    in.

24
Boxes
  • Java also provides a container, called Box, which
    is just like GridLayout, but forces either rows
    OR columns to be 1, so you either have a single
    column or a single row.
  • Box b Box.createHorizontalBox()
  • -or-
  • Box b Box.createVerticalBox()
  • Then, add components in the usual way
  • b.add(OKButton)
  • b.add(CancelButton)
  • Box b Box.createHorizontalBox()
  • Horizontal Boxes are arranged left to right,
    Vertical Boxes, from top to bottom

25
Boxes
  • So why not just make a GridLayout, with either
    rows or columns are 1?
  • Boxes have a few more things that GridLayout
    lacks.
  • We can insert something into a Box called a
    strut, which will make all boxes some minimum
    size.

26
Boxes
  • Depending on if you want to make your box have a
    minimum height or a minimum width, you can create
    either horizontal or vertical struts.
  • Box someBoxBox.createHorizontalBox() someBox.
    add(component1)
  • someBox.add(Box.createHorizontalStrut(10))
  • someBox.add(component2)
  • -or-
  • Box someBoxBox.createVerticalBox() someBox.ad
    d(component1)
  • someBox.add(Box.createVerticalStrut(10))
  • someBox.add(component2)

27
Boxes
  • You can also add vertical structs to horizontal
    boxes, and vice versa.
  • You can also add something called a Rigid Area,
    which will set a minimum height AND width for the
    box.
  • b.add(Box.createRigidArea(new Dimension(5,20))

28
Boxes
  • We can also add something between components to
    push them away from each other, to make them
    consume up as much space as possible vertically
    or horizontally.
  • Sun may have picked about the most counter
    intuitive word for this ever, and called it glue.
    (This ranks up there with two planes almost
    colliding in mid-air being called a near-miss)
    Why they wouldnt stick with the engineering
    terms, and call this maybe a Spring?

29
Boxes
  • Anyhow, this glue expands to fill as much space
    between components as it can.
  • someBox.add(button1)
  • someBox.add(Box.createGlue())
  • someBox.add(button2)
  • Also, BoxLayout can be assigned to a container
    just like any other Layout. Its just usually
    more convenient to use this provided Box class.

30
GridBagLayout
  • The mother of all Layout Managers. Its an
    absolute beast, in terms of flexibility and in
    terms of the code youll write just to get one
    working.
  • Use this only if you really need to. (read a
    very large amount of GUI elements)
  • Basically, it is a Grid Layout without any
    restrictions. Cells can be different sizes.
    They can resize differently than each other.
    Its a regular party.

31
GridBagLayout
  • To use, first, set the Layout Manager as a Grid
  • Bag Constraints
  • somePanel.setLayout(new GridBagLayout())
  • You then need to create an object of the class
    GridBagConstraints for each object you create,
    and use this as the 2nd argument of the add()
    (where the component itself is the 1st
    argument.)
  • Lost yet? Lets look at an example

32
GridBag Layout
  • somePanel.setLayout(new GridBagLayout())
  • GridBagConstraints c new GridBagConstraints()
  • c.weightx 100
  • c.weighty 100
  • c.gridx 0
  • c.gridy 2
  • c.gridWidth 2
  • c.gridHeight 1
  • c.fill GridBagConstraints.BOTH
  • c.anchor GridBagConstraints.CENTER
  • panel.add(someComponent, c)
  • Observation Lot of code to write, and you have
    to do this for every single component you add.

33
GridBag Layout
  • gridx and gridy specify which cell to place the
    top left most part of that component in. Cells
    numbering starts at 0,0.
  • gridWidth and gridHeight specify how many cells
    to take up. So now we can have a component
    stretch itself over 9 different cells by making
    Width and Height both 3.
  • The weightx and weighty fields specify the
    resizing properties. If the weight is set to
    zero, the cell is never grown or shrunk.

34
GridBag Layout
  • If you do not want a component to grow to fill
    the entire cell, set the fill constraint. You
    have four options for this field
  • GridBagConstraints.NONE no resizing
  • GridBagConstraints.HORIZONTAL stretch the
    component to fill the horizontal dimension of the
    cell
  • GridBagConstraints.VERTICAL stretch the
    component to fill the vertical dimension of the
    cell
  • GridBagConstraints.BOTH stretch the component
    to completely fill the dimensions of the cell

35
GridBag Layout
  • If the component does not completely fill the
    cell, set the anchor constraint
  • GridBagConstraints.CENTER center the component
    in the cell (default value)
  • GridBagConstraints.NORTH center the component
    in the cell horizontally and place it at the top
    in the vertical direction
  • GridBagConstraints.NORTHEAST top in the
    vertical direction and all the way to the left
  • and so forth

36
GridBag Layout in practice
  • The get complicated real fast. To create one,
    first
  • Sketch what you want in your head down on paper.
    Number the boxes (0,0), etc. This will make it a
    lot easier to implement (if your layout is so
    simple you dont need to do this, use something
    other than GridBagLayout)
  • Set all weights to 100. If you want a row or
    column to never be resized, set the
    weightx/weighty to 0 in all components in that
    row/column.
  • Triple check that what you have on paper is what
    you coded.
  • Compile, run, see what went wrong.
  • Fix problems, repeat as necessary

37
Layout Managers
  • Show of hands who doesnt ever want to use one
    of these?
  • Well, Java can do that too. You can use absolute
    positioning. Set the LayoutManager to null, and
    call setSize(width,height) and setLocation(x,y)
    on all of your components.
  • This is called Absolute Positioning.
  • Try to not do this. This leads to a very
    inflexible solution. Imagine what would happened
    if you resized your favorite windows application,
    and nothing ever resized.
Write a Comment
User Comments (0)
About PowerShow.com