Graphics – Part 2

Part 2 – Unit 5: Graphics (OPTIONAL: Computer Science 30S)

If you don’t feel like reading this web page, here are two alternatives:

  • Read this presentation of the same content (slides 23 – 32)
  • Watch this playlist of videos of the same content on YouTube

Content Sections:

  1. Adding Controls to a Container

Adding Controls to a Container

  • Now that we can create containers, we need to also create controls and add them into the container
  • Controls are also items that we can “import” from APIs like Swing and AWT, so adding to our example…


  • Here the control is added as an encapsulated property of the class


  • Now we need to instantiate it within the constructor by calling the JLabel constructor and setting any properties we need


  • You saw in the overloaded constructor options that JLabels also support images
  • But although we have instantiated the control, it is not yet added to the container
  • To do this, we have to consider how the container will draw (render) the control (where? and size?)
  • The swing JFrame container uses another container within called the “content pane” to contain the controls (the word “pane” comes from “window pane” so it means the “content” in the “window”)
  • To access this, we use a method


  • Once we have access to the container, we use a swing “layout manager” which works with the container to determine the position and size of components
  • We set the layout manager with a method, and we have choices:
    • BorderLayout – automatically puts components in one of 5 areas (top, bottom, left, right, and center) of the container


    • BoxLayout – automatically puts components in a single row or column of the container


    • CardLayout – is often controlled by another component


    • FlowLayout – automatically puts components in a single row and then flows over when needed to the next row (this is the default)


    • GridBagLayout – puts components in a grid of cells


    • GridLayout – automatically puts components in equal size and places in rows and columns


    • GroupLayout – works with other layouts separately


    • SpringLayout – lets you specify the relationships between the edges of components to each other


    • null – does not specify the size or position, so you must then do it


  • Once we have the layout set, we can add controls into the container:


  • Let’s expand out our example and add a icon graphic (we had previously seen a preview of how to do this in a previous unit on arrays)


  • We can add different controls in different ways and set different layouts for our container to start creating a GUI



If you understood this content, you should move forward to the examples page, or go back to the content page and look it over again!