window systems, layouts and toolkits iat351 · windows and layouts | iat351 | february 1, 2008...

46
1 Window systems, layouts and toolkits IAT351 Week 3 Lecture 2 1.02.2008 Lyn Bartram [email protected] Some slides adapted from K. Edwards, Georgia tech Windows and Layouts | IAT351 | February 1, 2008 Today’s agenda Administrivia Window system architectures Toolkits and window system interplay Layout Managers Drawing in java Outcome: Extending Swing and making your own components Custom drawing Assignment 2!

Upload: others

Post on 23-Sep-2020

0 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Window systems, layouts and toolkits IAT351 · Windows and Layouts | IAT351 | February 1, 2008 Window Systems: a little history • The BitBlt algorithm Dan Ingalls, “Bit Block

1

Window systems, layouts and toolkitsIAT351

Week 3 Lecture 21.02.2008

Lyn [email protected]

Some slides adapted from K. Edwards, Georgia tech

Windows and Layouts | IAT351 | February 1, 2008

Today’s agenda

• Administrivia• Window system architectures

Toolkits and window system interplay• Layout Managers• Drawing in java• Outcome:

Extending Swing and making your own components Custom drawing Assignment 2!

Page 2: Window systems, layouts and toolkits IAT351 · Windows and Layouts | IAT351 | February 1, 2008 Window Systems: a little history • The BitBlt algorithm Dan Ingalls, “Bit Block

2

Windows and Layouts | IAT351 | February 1, 2008

Administriva

• Assignment 1 due by midnight• Assignment 2 now posted on the website

• Extend your Assignment 1 in 2 critical ways:1. Custom components - make a PhotoComponent for your photo panel Use more sophisticated layout management2. Add in custom drawing and text¡ Support freehand and text annotations on your photos

¡ Due at midnight in two weeks

Windows and Layouts | IAT351 | February 1, 2008

Interactive System LayersSpecialised graphics or devices

OS services

Page 3: Window systems, layouts and toolkits IAT351 · Windows and Layouts | IAT351 | February 1, 2008 Window Systems: a little history • The BitBlt algorithm Dan Ingalls, “Bit Block

3

Windows and Layouts | IAT351 | February 1, 2008

But we ended up with …

OS

Windows and Layouts | IAT351 | February 1, 2008

Window Systems

• Output and input are usually done in the context of a windowingsystem

• Should be familiar to all• Developed to support metaphor of overlapping pieces of paper on

a desk Hand in glove with the desktop metaphor Good use of limited space Leverages human memory Rich conceptual model

• Useful programmming abstraction BUT introduces enormousmanagement issues

Page 4: Window systems, layouts and toolkits IAT351 · Windows and Layouts | IAT351 | February 1, 2008 Window Systems: a little history • The BitBlt algorithm Dan Ingalls, “Bit Block

4

Windows and Layouts | IAT351 | February 1, 2008

Window Systems: a little history

• The BitBlt algorithm Dan Ingalls, “Bit Block Transfer” (same guy invented popup menus)

• Introduced in SmallTalk 80• Enabled real-time interaction with windows in the UI• Why is this important?

Supported fast transfer of bits from main memory anddisplay memory

Overlapping windows have lots of “damage”, need lots ofrepainting

• Requires fast transfer• XeroX Alto had a BitBlt hardware instruction

Windows and Layouts | IAT351 | February 1, 2008

Goals of the window system

• Virtual devices and virtual displays

• Virtual displays Multiple raster surfaces to draw on Implemented on a single raster surface Each window is its own context, with own coordinate system and

potentially colour palette• Illusion of contiguous non-overlapping surfaces :

Each drawing surface is added to the drawing memory overhead

Page 5: Window systems, layouts and toolkits IAT351 · Windows and Layouts | IAT351 | February 1, 2008 Window Systems: a little history • The BitBlt algorithm Dan Ingalls, “Bit Block

5

Windows and Layouts | IAT351 | February 1, 2008

Virtual devices

• Also multiplexes physical input devices• Helps to provide device abstractions for higher-level, simulated

devices Can you think of an example?

• Provides a way of optimising the used of limited resources Screen space Input devices

• Strong analogy to operating systems Centralised support within the OS

Windows and Layouts | IAT351 | February 1, 2008

Window system goal: uniformity

• Maintain consistency and uniformity across applications 2 interfaces: UI and API User interface Application programming interface

• Uniformity of the UI Consistent “face” to the user Allows/enforces some consistency across applications Combination of guidelines and practice - hard to enforce Mostly done by providing access to tools andmethods - The job of the toolkit

Page 6: Window systems, layouts and toolkits IAT351 · Windows and Layouts | IAT351 | February 1, 2008 Window Systems: a little history • The BitBlt algorithm Dan Ingalls, “Bit Block

6

Windows and Layouts | IAT351 | February 1, 2008

Uniformity cont.

• Uniformity of the API Provides the virtual device abstraction Carries out the low-level operations

• Drawing• Input processing• Independent of actual devices

Typically provides mechanisms to integrate applications• Minimum: cut and paste• Synchronise (make a new folder in file system during a save)

Windows and Layouts | IAT351 | February 1, 2008

Other issues in window systems

• Hierarchical windows Some systems allow windows within windows

• Don’t have to stick to analogs of physical display devices MDI (Multiple Document Interface

• Need at least 2 levels of hierarchy “root” window and “child” (app objects) windows

• Hierarchy turns out to not be that useful Same functionality using toolkit containers More flexible

Page 7: Window systems, layouts and toolkits IAT351 · Windows and Layouts | IAT351 | February 1, 2008 Window Systems: a little history • The BitBlt algorithm Dan Ingalls, “Bit Block

7

Windows and Layouts | IAT351 | February 1, 2008

Issue: damage/redraw

• Windows suffer “damage” when they are obscured and then re-exposed resized

Redraw!

Windows and Layouts | IAT351 | February 1, 2008

Issue: damage/redraw

• How much is exposed?• System may or may not maintain and/or restore obscured portions

of windows “retained contents” model For non-retained contents, application has to be asked to

recreate/redraw damaged parts• Have to be prepared to redraw anyway since larger windows

create a new content area• But retained contents model still very convenient and efficient

Not available in AWT Optional in Swing

Page 8: Window systems, layouts and toolkits IAT351 · Windows and Layouts | IAT351 | February 1, 2008 Window Systems: a little history • The BitBlt algorithm Dan Ingalls, “Bit Block

8

Windows and Layouts | IAT351 | February 1, 2008

Output in toolkits

• Like most things, output is organised around the interactor treestructure (wait for the input Each object knows how to draw and do tasks specific to what it is Each object knows what children it has and what their capabilities are Generic tasks specialised to specific subclasses

Windows and Layouts | IAT351 | February 1, 2008

Interactor Tree Display Screen

Outer Win [black]

Result Win [tan]Result String

Inner Win [green]

Keypad [Teal]

- button

+ button

0 button

= button

7 8 9

4 5 6

0 + -

1 2 3

=

93.54

ENT

Page 9: Window systems, layouts and toolkits IAT351 · Windows and Layouts | IAT351 | February 1, 2008 Window Systems: a little history • The BitBlt algorithm Dan Ingalls, “Bit Block

9

Windows and Layouts | IAT351 | February 1, 2008

Damage

• Interactors draw on a certain screen area• When screen image changes, need to schedule a redraw

Typically don’t want to “just draw it” because others will overlap oraffect it

Want to optimise redraw Add to display list/redraw list

Windows and Layouts | IAT351 | February 1, 2008

Damage

• Typical scheme ( and Swing does this) is to have each objectreport its own damage Tells parent, which tells parent, up the tree Collects all the damaged regions at the top Typically batches them and determines which actually need to be

redrawn Normally one enclosing rectangle

• 2 kinds of damage in Swing Layout changes (a component may be added or deleted) State changes, drawing updates

Page 10: Window systems, layouts and toolkits IAT351 · Windows and Layouts | IAT351 | February 1, 2008 Window Systems: a little history • The BitBlt algorithm Dan Ingalls, “Bit Block

10

Windows and Layouts | IAT351 | February 1, 2008

(Re)Draw

• Each object knows how to create its own appearance Local drawing Requests children to draw themselves

• Systems vary in detail such as coordinate systems and clipping

• User-custom drawing *may* need to handle damage explicitly within object

repaint()• paintComponent() never called directly!

validate(), pack() - when layout changes

Windows and Layouts | IAT351 | February 1, 2008

Redraw

• System schedules a redraw in response to damage• When redraw done, first the system needs to ensure that

everything is in the right place and is the right size

• ----> Layout management

Page 11: Window systems, layouts and toolkits IAT351 · Windows and Layouts | IAT351 | February 1, 2008 Window Systems: a little history • The BitBlt algorithm Dan Ingalls, “Bit Block

11

Windows and Layouts | IAT351 | February 1, 2008

Layout Management

• The process of determining the size and position of components.

• Layout management can be done using absolute positioning Size and position of every component within the container must be

specified. Does not adjust well when the top-level container is resized. Does not adjust well to differences between users and systems, such

as font size.

Windows and Layouts | IAT351 | February 1, 2008

Layout Management (cont)

• Layout management is often performed using layoutmanagers Components can provide size and position hints to layout

managers, but layout managers have the final say on the sizeand position of those components.

Page 12: Window systems, layouts and toolkits IAT351 · Windows and Layouts | IAT351 | February 1, 2008 Window Systems: a little history • The BitBlt algorithm Dan Ingalls, “Bit Block

12

Windows and Layouts | IAT351 | February 1, 2008

Layout Management (cont)

• Layout hints Minimum, preferred and maximum size X axis alignment, Y axis alignment

• Customizing layout hints Invoking setter methods: setMinimumSize, setAlignmentX, ... Subclassing and overriding the getter methods: getMinimumSize,

getAlignmentX, ...

Windows and Layouts | IAT351 | February 1, 2008

Layout Management (cont)

• Java’s layout managers provide a level of abstraction toautomatically map your user interface on all windowing systems.

• The GUI components are placed in containers. Each containerhas a layout manager to arrange the GUI components within thecontainer.

• The Java platform supplies five commonly used layout managers: BorderLayout BoxLayout FlowLayout GridLayout GridBagLayout

Page 13: Window systems, layouts and toolkits IAT351 · Windows and Layouts | IAT351 | February 1, 2008 Window Systems: a little history • The BitBlt algorithm Dan Ingalls, “Bit Block

13

Windows and Layouts | IAT351 | February 1, 2008

Layout Managers

Layout Managers are set in containers. The syntax to set a layoutmanager is:

container.setLayout(new SpecificLayout( ) );

To add a component to a container, use the add method:

JButton jbtOK = new JButton (“OK”); container.add (jbtOK);

The container can be a content pane of a frame or an applet, or aninstance of JPanel.

Windows and Layouts | IAT351 | February 1, 2008

Layout Managers

Another Example:

• Set FlowLayout, aligned Left with a Horizontal gap of 10 pixels anda Vertical gap of 20 pixels between components. JPanel myPane = getContentPane ( ); myPane.setLayout (new FlowLayout (FlowLayout,LEFT, 10, 20);

Page 14: Window systems, layouts and toolkits IAT351 · Windows and Layouts | IAT351 | February 1, 2008 Window Systems: a little history • The BitBlt algorithm Dan Ingalls, “Bit Block

14

Windows and Layouts | IAT351 | February 1, 2008

Layout Managers

• Layout Managers are responsible for arranging Components suchas: buttons, labels,lists, combo boxes, text fields,text areas,

textboxes, check boxes, radio buttons etc.

• Every Container has a LayoutManager by default, which can bechanged if needed as follows:

Container c = getContentPane();

c.setLayout( new SpecificLayout ( ) ); // such as FlowLayout

Windows and Layouts | IAT351 | February 1, 2008

Layout Managers in the Java API

• Basic Layout Managers in the Java API

Flow Layout (arrange components in left-to-right order)

Grid Layout (arrange components in a grid matrix)

Border Layout (divide window into 5 areas: E,W,N,S, Center)

Box Layout (Organizes components into a single row or column)

Card Layout (Organizes components into one area such that onlyone is visible at any time.)

GridBag Layout (Organizes components into a grid of cells,allowing components to span more than one cell. )

Page 15: Window systems, layouts and toolkits IAT351 · Windows and Layouts | IAT351 | February 1, 2008 Window Systems: a little history • The BitBlt algorithm Dan Ingalls, “Bit Block

15

Windows and Layouts | IAT351 | February 1, 2008

FlowLayout Example

A program that adds threelabels and text fields into thecontent pane of a frame with aFlowLayout manager.

Note layout change with resize

Windows and Layouts | IAT351 | February 1, 2008

The FlowLayout Class

java.awt.FlowLayout

-alignment: int

-hgap: int

-vgap: int

+FlowLayout()

+FlowLayout(alignment: int)

+FlowLayout(alignment: int, hgap:

int, vgap: int)

The alignment of this layout manager (default: CENTER).

The horizontal gap of this layout manager (default: 5 pixels).

The vertical gap of this layout manager (default: 5 pixels).

Creates a default FlowLayout manager.

Creates a FlowLayout manager with a specified alignment.

Creates a FlowLayout manager with a specified alignment, horizontal gap, and vertical gap.

The get and set methods for these data fields are provided in

the class, but omitted in the UML diagram for brevity.

Page 16: Window systems, layouts and toolkits IAT351 · Windows and Layouts | IAT351 | February 1, 2008 Window Systems: a little history • The BitBlt algorithm Dan Ingalls, “Bit Block

16

Windows and Layouts | IAT351 | February 1, 2008

FlowLayout

• The FlowLayout manager arranges components across the screenfrom left to right, when one row is full, it starts filling up the nextrow.

• FlowLayout constructors public FlowLayout (int align, int hGap, int vGap)

• Constructs a new FlowLayout with the specified alignment,horizontal gap, and vertical gap (in pixels)

public FlowLayout (int alignment)• Constructs a new FlowLayout with the specified alignment and

with default gaps of 5 pixels horizontally and vertically. public FlowLayout ( )

• Constructs a new FlowLayout with default alignment, leftalignment, and default gap of 5 pixels, between components

Windows and Layouts | IAT351 | February 1, 2008

ShowFlowLayout.java

// ShowFlowLayout.java: Demonstrate using FlowLayoutimport javax.swing.JButton;import javax.swing.JFrame;import java.awt.Container;import java.awt.FlowLayout;

public class ShowFlowLayout extends JFrame{ public ShowFlowLayout( ) // Default constructor { // Get the content pane of the frame Container container = getContentPane();

// Set FlowLayout, aligned left with horizontal gap 10 // and vertical gap 20 between components container.setLayout(new FlowLayout(FlowLayout.LEFT, 10,

20));

// Add buttons to the frame for (int i=1; i<=10; i++) container.add(new JButton("Component " + i)); }

// Main method public static void main(String[ ] args) { ShowFlowLayout frame = new

ShowFlowLayout(); frame.setTitle("Show FlowLayout");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setSize(400, 350); // Width, height inpixels

frame.setVisible(true); } // End of main method} // End of class ShowFlowLayout

Page 17: Window systems, layouts and toolkits IAT351 · Windows and Layouts | IAT351 | February 1, 2008 Window Systems: a little history • The BitBlt algorithm Dan Ingalls, “Bit Block

17

Windows and Layouts | IAT351 | February 1, 2008

ShowFlowLayout.java comments

The previous program creates a class named ShowFlowLayout thatextends the Jframe class. The constructor of ShowFlowLayoutconstructs and places the components in the frame using theFlowLayout manager.

An anonymous FlowLayout object was created in the statement:

container.setLayout(new FlowLayout(FlowLayout.LEFT, 10, 20));

The above code is equivalent to:FlowLayout layout = new FlowLayout();container.setLayout(layout);

Windows and Layouts | IAT351 | February 1, 2008

ShowFlowLayout.java comments

• The setTitle method in the previous program is defined in thejava.awt.Frame class, and since JFrame is a subclass of Frame,you can use it to set a title for an object of JFrame.

frame.setTitle("Show FlowLayout");

• Remember to put the new operator before LayoutManager whensetting a layout style.

For example, setLayout(new FlowLayout(FlowLayout.LEFT, 10, 20));

Page 18: Window systems, layouts and toolkits IAT351 · Windows and Layouts | IAT351 | February 1, 2008 Window Systems: a little history • The BitBlt algorithm Dan Ingalls, “Bit Block

18

Windows and Layouts | IAT351 | February 1, 2008

GridLayout Example

Rewrite the program in thepreceding example using aGridLayout manager instead of aFlowLayout manager to displaythe labels and text fields.

Windows and Layouts | IAT351 | February 1, 2008

The GridLayout Class

java.awt.GridLayout

-rows: int

-columns: int

-hgap: int

-vgap: int

+GridLayout()

+GridLayout(rows: int, columns: int)

+GridLayout(rows: int, columns: int, hgap: int, vgap: int)

The number of rows in this layout manager (default: 1).

The number of columns in this layout manager (default: 1).

The horizontal gap of this layout manager (default: 0).

The vertical gap of this layout manager (default: 0).

Creates a default GridLayout manager.

Creates a GridLayout with a specified number of rows and columns.

Creates a GridLayout manager with a specified number of rows and

columns, horizontal gap, and vertical gap.

The get and set methods for these data fields are provided in the class, but omitted in the UML diagram for brevity.

Page 19: Window systems, layouts and toolkits IAT351 · Windows and Layouts | IAT351 | February 1, 2008 Window Systems: a little history • The BitBlt algorithm Dan Ingalls, “Bit Block

19

Windows and Layouts | IAT351 | February 1, 2008

GridLayout Manager

• GridLayout divides the container into a grid (matrix) of equal sizecells and arranges the components left to right, and row after row.

• GridLayout manager has 3 constructors: pubic GridLayout(int rows, int columns, int hGap, int vGap)

• Contructs a GridLayout with the specified number of rows andcolumns, and horizontal gap, and vertical gap betweencomponents

public GridLayout(int rows, int columns)• Constructs a GridLayout with the specified number of rows and

columns. The horizontal and vertical gaps are zero. public GridLayout()

• Constructs a GridLayout with one row, one column; one cell

Windows and Layouts | IAT351 | February 1, 2008

GridLayout Manager

// ShowGridLayout.java: Demonstrate using GridLayoutimport javax.swing.JButton;import javax.swing.JFrame;import java.awt.GridLayout;import java.awt.Container;

public class ShowGridLayout extends JFrame{

Page 20: Window systems, layouts and toolkits IAT351 · Windows and Layouts | IAT351 | February 1, 2008 Window Systems: a little history • The BitBlt algorithm Dan Ingalls, “Bit Block

20

Windows and Layouts | IAT351 | February 1, 2008

GridLayout Manager

public ShowGridLayout() // Default constructor { // Get the content pane of the frame Container container = getContentPane(); // Set GridLayout, 4 rows, 3 columns, and gaps of 5 pixels between // components horizontally and vertically container.setLayout(new GridLayout(4, 3, 5, 5)); // Add buttons to the frame for (int i=1; i<=10; i++) container.add(new JButton("Component " + i)); }

Windows and Layouts | IAT351 | February 1, 2008

GridLayout Manager

// Main method public static void main(String[ ] args) { ShowGridLayout frame = new ShowGridLayout(); frame.setTitle("Show Java GridLayout"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(200, 200); // 200 pixels wide by 200 pixels high frame.setVisible(true); // make it visible } // End of main method} // End of class ShowGridLayout

Page 21: Window systems, layouts and toolkits IAT351 · Windows and Layouts | IAT351 | February 1, 2008 Window Systems: a little history • The BitBlt algorithm Dan Ingalls, “Bit Block

21

Windows and Layouts | IAT351 | February 1, 2008

The BorderLayout Manager

The BorderLayout manager divides thecontainer into five areas: East, South,West, North, and Center. Componentsare added to a BorderLayout by usingthe add method.

add(Component, constraint), whereconstraint is BorderLayout.EAST,BorderLayout.SOUTH,BorderLayout.WEST,BorderLayout.NORTH, orBorderLayout.CENTER.

Windows and Layouts | IAT351 | February 1, 2008

BorderLayout Example

Page 22: Window systems, layouts and toolkits IAT351 · Windows and Layouts | IAT351 | February 1, 2008 Window Systems: a little history • The BitBlt algorithm Dan Ingalls, “Bit Block

22

Windows and Layouts | IAT351 | February 1, 2008

The BorderLayout Class

java.awt.BorderLayout

-hgap: int

-vgap: int

+BorderLayout()

+BorderLayout(hgap: int, vgap: int)

The horizontal gap of this layout manager (default: 0).

The vertical gap of this layout manager (default: 0).

Creates a default BorderLayout manager.

Creates a BorderLayout manager with a specified number of

horizontal gap, and vertical gap.

The get and set methods for these data fields are provided in the class, but omitted in the UML diagram for brevity.

Windows and Layouts | IAT351 | February 1, 2008

BorderLayout Manager

• BorderLayout manager divides the window into 5 areas: North,South, East, West, and Center

• Components are added by indicating which area they should beplaced in add(componentName, index); where index is a constant BorderLayout.EAST, BorderLayout.WEST,

BorderLayout.SOUTH, BorderLayout.NORTH, orBorderLayout.CENTER

• BorderLayout Constructors public BorderLayout(int hGap, int vGap) // gaps (in pixels) public BorderLayout() - with no horizontal or vertical gaps between

components

Page 23: Window systems, layouts and toolkits IAT351 · Windows and Layouts | IAT351 | February 1, 2008 Window Systems: a little history • The BitBlt algorithm Dan Ingalls, “Bit Block

23

Windows and Layouts | IAT351 | February 1, 2008

BorderLayout Manager

• Note: BorderLayout interprets the absence of an index as

BorderLayout.CENTER. For example, add(component) is the same as add(component, BorderLayout.CENTER)

If you add 2 components into a container of the BorderLayout, thenonly the last component is displayed:

container.add(component1); // Example: container.add(jbtOK); container.add(component2); // Example:

container.add(jbtCancel);Then, only the Cancel button is displayed !

Windows and Layouts | IAT351 | February 1, 2008

BorderLayout Manager

// ShowBorderLayout.java: Demonstrate using BorderLayoutimport javax.swing.JButton;import javax.swing.JFrame;import java.awt.Container;import java.awt.BorderLayout;

public class ShowBorderLayout extends JFrame {

Page 24: Window systems, layouts and toolkits IAT351 · Windows and Layouts | IAT351 | February 1, 2008 Window Systems: a little history • The BitBlt algorithm Dan Ingalls, “Bit Block

24

Windows and Layouts | IAT351 | February 1, 2008

BorderLayout Manager

public ShowBorderLayout( ) // Default constructor { // Get the content pane of the frame Container container = getContentPane( ); // Set BorderLayout with horizontal gap of 5 and vertical gap of 10 pixels container.setLayout(new BorderLayout(5, 10)); // Add buttons to the frame container.add(new JButton("East"), BorderLayout.EAST); container.add(new JButton("South"), BorderLayout.SOUTH); container.add(new JButton("West"), BorderLayout.WEST); container.add(new JButton("North"), BorderLayout.NORTH); container.add(new JButton("Center"), BorderLayout.CENTER); }

Windows and Layouts | IAT351 | February 1, 2008

BorderLayout Manager

// Main method public static void main(String[ ] args) { ShowBorderLayout frame = new ShowBorderLayout(); frame.setTitle("Show BorderLayout"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(300, 200); // 300 pixels wide by 200 pixels high frame.setVisible(true); } // End of main} // End of class ShowBorderLayout

Page 25: Window systems, layouts and toolkits IAT351 · Windows and Layouts | IAT351 | February 1, 2008 Window Systems: a little history • The BitBlt algorithm Dan Ingalls, “Bit Block

25

Windows and Layouts | IAT351 | February 1, 2008

BoxLayout

• Places components in a single row (left to right) or column (top tobottom).

• Respects component’s maximum size and alignment hints.

Windows and Layouts | IAT351 | February 1, 2008

CardLayout Manager

The CardLayout manager arranges components in a queue ofcards, but you can see only one card at a time.

To construct a CardLayout, use the constructor CardLayout() Cards are placed in a container such as a panel.

Components are placed in the card queue in the order in whichthey are added.

Example: You can construct source object buttons such as: FIRST NEXT PREVIOUS LAST IMAGES [ 10 ]

Page 26: Window systems, layouts and toolkits IAT351 · Windows and Layouts | IAT351 | February 1, 2008 Window Systems: a little history • The BitBlt algorithm Dan Ingalls, “Bit Block

26

Windows and Layouts | IAT351 | February 1, 2008

Layout Managers: GridBagLayout Manager

The GridBagLayout manager is the most flexible and most complex.

It is similar to the GridLayout manager because both layoutmanagers arrange components into a grid.

The components of GridBagLayout can vary in size, however.

The components can be added in any order.

Windows and Layouts | IAT351 | February 1, 2008

GridBagLayout

• Divides the window into grids, without requiring the components to be thesame size

• About three times more flexible than the other standard layout managers,but nine times harder to use

• Each component managed by a grid bag layout is associated with aninstance of GridBagConstraints

• The GridBagConstraints specifies: How the component is laid out in the display area In which cell the component starts and ends How the component stretches when extra room is available Alignment in cells

• Java 5 introduced SpringLayout, with similar power but much lesscomplexity

Page 27: Window systems, layouts and toolkits IAT351 · Windows and Layouts | IAT351 | February 1, 2008 Window Systems: a little history • The BitBlt algorithm Dan Ingalls, “Bit Block

27

Windows and Layouts | IAT351 | February 1, 2008

Windows and Layouts | IAT351 | February 1, 2008

Using Panels as Containers

• JPanel is a container with FlowLayout as the default LayoutManager

• It is a container that can be placed into another container.• Panels are invisible containers that are used as small containers to

group components to achieve a desired look and feel• As a single layout manager by itself, JPanel is not sufficient to

produce a GUI.• Different areas of a window can be arranged differently with

different layout managers by using JPanel.• Each panel can be set to use a different Layout Manager

Page 28: Window systems, layouts and toolkits IAT351 · Windows and Layouts | IAT351 | February 1, 2008 Window Systems: a little history • The BitBlt algorithm Dan Ingalls, “Bit Block

28

Windows and Layouts | IAT351 | February 1, 2008

Using Panels as Containers

• The constructor in the JPanel class is JPanel( )• To add a button to the panel p, you can use:

JPanel p = new JPanel ( ); p.add(new JButton(“Button Name”)); JFrame myFrame = new JFrame ( ); // Create a new frame

• By default, JPanel uses FlowLayout. Panels can be inside a frameor inside another panel. The following statement places panel pinto frame myFrame. myFrame.getContentPane( ).add(p);

Windows and Layouts | IAT351 | February 1, 2008

Using Panels as Containers

// TestPanels.java: Use panels to group componentsimport java.awt.*; // Construct “microwave oven”

Example 12.4import javax.swing.*;

public class TestPanels extends JFrame{ // Default constructor public TestPanels( ) {

Container container = getContentPane(); // Set BorderLayout for the frame container.setLayout(new BorderLayout());

// Create panel p1 for the buttons and set GridLayout JPanel p1 = new JPanel(); p1.setLayout(new GridLayout(4, 3)); // 4 rows, 3

columns

// Add 12 buttons to the panel p1 ( 9 and then 3 more …) for (int i=1; i<=9; i++) { p1.add(new JButton(" " + i)); } p1.add(new JButton(" " + 0)); // Add the zero button p1.add(new JButton("Start")); // Add the Start button p1.add(new JButton("Stop")); // Add the Stop button// Create panel p2 to hold a text field and also panel p1 JPanel p2 = new JPanel( ); // Create a new panel

p2 p2.setLayout(new BorderLayout( ) ); p2.add(new JTextField("Time to be displayed here"), BorderLayout.NORTH); p2.add(p1, BorderLayout.CENTER); // Add panel p1

to panel p2

// Add p2 and a big button to the frame (left side offrame)

container.add(p2, BorderLayout.EAST); // Add panelp2 to left side of frame

container.add(new Button("Food to be placed here"), BorderLayout.CENTER); // Add big button with text

message } // End of default constructor

Page 29: Window systems, layouts and toolkits IAT351 · Windows and Layouts | IAT351 | February 1, 2008 Window Systems: a little history • The BitBlt algorithm Dan Ingalls, “Bit Block

29

Windows and Layouts | IAT351 | February 1, 2008

Using Panels as Containers

// Main method public static void main(String[ ] args) { TestPanels frame = new TestPanels(); frame.setTitle("The Front View of a Microwave Oven"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(400, 250); // 400 pixels wide by 250 pixels high frame.setVisible(true); // make it visible } // End of main method} // End of class TestPanels

Windows and Layouts | IAT351 | February 1, 2008

Creating Frames and Panels usingFlowLayoutimport java.awt.*;import java.awt.event.*;import javax.swing.*;public class SomeButtons extends JFrame implements ActionListener { private JButton jbt1, jbt2, jbt3, jbt4; public static void main(String[ ] args) { ButtonFrame frame = new ButtonFrame ( ) frame.pack( ); frame.setTitle(“Some Buttons"); frame.setVisible(true); } // End of main method

Page 30: Window systems, layouts and toolkits IAT351 · Windows and Layouts | IAT351 | February 1, 2008 Window Systems: a little history • The BitBlt algorithm Dan Ingalls, “Bit Block

30

Windows and Layouts | IAT351 | February 1, 2008

Creating Frames and Panels usingFlowLayoutpublic ButtonFrame ( ) { JPanel p1 = new JPanel(); // Create panel p1, add 2 buttons p1.setLayout (new FlowLayout( ) ); p1.add(jbt1 = new JButton("Button 1")); p1.add(jbt2 = new JButton("Button 2"));

JPanel p2 = new JPanel( ); // Create panel p2; add 2 more buttons p2.setLayout(new FlowLayout()); p2.add(jbt3 = new JButton("Button 3")); p2.add(jbt4 = new JButton("Button 4"));

Windows and Layouts | IAT351 | February 1, 2008

Creating Frames and Panels usingFlowLayout// Place panels p1 and p2 into the frame of class ButtonFrame getContentPane().setLayout(new FlowLayout()); getContentPane().add(p1); getContentPane().add(p2);

jbt1.addActionListener(this); // Register listeners for the 4 buttons jbt2.addActionListener(this); jbt3.addActionListener(this); jbt4.addActionListener(this);

Page 31: Window systems, layouts and toolkits IAT351 · Windows and Layouts | IAT351 | February 1, 2008 Window Systems: a little history • The BitBlt algorithm Dan Ingalls, “Bit Block

31

Windows and Layouts | IAT351 | February 1, 2008

Creating Frames and Panels usingFlowLayoutpublic void actionPerformed(ActionEvent e) { System.out.println(e.getActionCommand() + " was clicked"); }

} // End of class SomeButtons

Windows and Layouts | IAT351 | February 1, 2008

Drawing Graphics in Panels

Another important use of JPanel is for drawing strings andgraphics.

To draw inside of a panel, you should create a new class thatextends JPanel and overrides the paintComponent to tell the panelhow to draw things.

It is recommended that you use JPanel to draw messages andshapes and to show images. This way, your drawing will notinterfere with other components.

The signature of the paintComponent method is:

public void paintComponent (Graphics g)

Page 32: Window systems, layouts and toolkits IAT351 · Windows and Layouts | IAT351 | February 1, 2008 Window Systems: a little history • The BitBlt algorithm Dan Ingalls, “Bit Block

32

Windows and Layouts | IAT351 | February 1, 2008

Drawing Graphics in Panels

The Graphics object g is created automatically by the Java runtimesystem.

You can use the various drawing methods defined in the Grpahicsclass to draw strings and geometric figures.

For example:, drawString(string, x1, y1);

Windows and Layouts | IAT351 | February 1, 2008

Drawing Graphics in Panels

//Display a message on a JPanelimport javax.swing.*; //import java.awt.*; //public class DrawMessage extends

JPanel { public static void main(String [ ]

args ) { JFrame frame = new JFrame

(“DrawMessage”); frame.getContentPane().add(new

DrawMessage());

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setSize(300, 200); frame.setVisible(true); }

// draws a message, “Welcome toJava!” in the middle of frame

public void paintComponent(Graphics g)

{

super.paintComponent(g);

g.drawString(“Welcome to Java!”, 40, 20); // x = 40, y = 20

}

} // End of class DrawMessage

Page 33: Window systems, layouts and toolkits IAT351 · Windows and Layouts | IAT351 | February 1, 2008 Window Systems: a little history • The BitBlt algorithm Dan Ingalls, “Bit Block

33

Windows and Layouts | IAT351 | February 1, 2008

Graphics Objects Drawing Shapes

• A Graphics object is made available to GUI components at runtime• The Graphics object is used to write, draw simple shapes, or

display images.• GUI components do not use System.out.println(), they use the

Graphics object instead.• Some commonly used methods of the Graphics object methods:

drawString(String str, int x, int y) drawLine(int x1, int y1, int x2, int y2) drawRect(int x, int y, int width, int height) fillRect(int x, int y, int width, int height) drawRoundRect (int x, int y, int wid, int hgt, int horDiam, int

verDiam) fillRoundRect (int x, int y, int wid, int hgt, int horDiam, int

verDiam)

Windows and Layouts | IAT351 | February 1, 2008

Graphics Objects (Graphics ObjectsMethods)

draw3DRect (int x, int y, int width, int height, boolean raised)

“raised” indicates whether the rectangle is raised or indentedfrom the

surface. (“raised” true or false)

drawOval(int x, int y, int width, int height)

drawArc(int x, int y, int width, int height, int startAngle, intarcAngle)

Page 34: Window systems, layouts and toolkits IAT351 · Windows and Layouts | IAT351 | February 1, 2008 Window Systems: a little history • The BitBlt algorithm Dan Ingalls, “Bit Block

34

Windows and Layouts | IAT351 | February 1, 2008

Color

• Color objects are used to set the color of GUI components• Color constructor

Color(int r, int g, int b)• Contructs a color object with the specified red, blue, and

green components in the range of 0 – 255 (0 is darkest, 255lightest shade)

• Example: Color myColor = new Color( 100, 50 , 150); The Color class has predefined colors that you can use, such as:

• Color.yellow, Color.gray, Color.cyan, Color.blue, Color.red,etc.

Example use of Color objects• myPanel.setBackground(myColor.orange);• myButton.setBackground(myColor.blue);• myPanel.setForeground(myColor.magenta);

Windows and Layouts | IAT351 | February 1, 2008

Color: Setting the Background Color

Setting the background color of a panel using Color color JPanel myPanel = new JPanel ( ); myPanel.setBackground(color); You can use one of the 13 standard colors (black, blue, cyan, dark gray,

gray, green, light gray, magenta, orange, pink, red, white, yellow) definedas constants in the java.awt.Color class.

JPanel myPanel = new JPanel ( ); // Create a new panel myPanel.setBackground(Color.blue); // Set background color to blue

Page 35: Window systems, layouts and toolkits IAT351 · Windows and Layouts | IAT351 | February 1, 2008 Window Systems: a little history • The BitBlt algorithm Dan Ingalls, “Bit Block

35

Windows and Layouts | IAT351 | February 1, 2008

Color

• Java also provides a JColorChooser, which is a GUI for graphicallychoosing a color.

• The code below calls the JColorChooser dialog, allowing the userto select a color. The selected color is returned and assigned.

• color = JColorChooser.showDialog(FrameExample2.this, "Choosing a color", color);

Windows and Layouts | IAT351 | February 1, 2008

The Font Class

Font myFont = Font (name, style, size);

Example:• Font myFont = new Font("SansSerif ", Font.BOLD, 16);

• Font myFont2 = new Font("Serif", Font.BOLD+Font.ITALIC, 12);

(specify both BOLD and ITALIC, size 12, and name “Serif”)

Page 36: Window systems, layouts and toolkits IAT351 · Windows and Layouts | IAT351 | February 1, 2008 Window Systems: a little history • The BitBlt algorithm Dan Ingalls, “Bit Block

36

Windows and Layouts | IAT351 | February 1, 2008

The Font Class

You can choose a font name from the following:

SanSerif, Serif, Monospaced, Dialog, or DialogInput

You can choose a font style from the following:

Font.PLAIN, Font.BOLD, Font.ITALIC

Windows and Layouts | IAT351 | February 1, 2008

The Font Class: Available Font Names

The following statements will print all available font names in the Java systemusing the abstract class GraphicsEnvironment

GraphicsEnvironment e = GraphicsEnvironment.getLocalGraphicsEnvironment ( );String [ ] fontnames = e.getAvailableFontFamilyNames ( );

for (int i = 0; i < fontnames.length; i++) System.out.println ( fontnames[i] );

Page 37: Window systems, layouts and toolkits IAT351 · Windows and Layouts | IAT351 | February 1, 2008 Window Systems: a little history • The BitBlt algorithm Dan Ingalls, “Bit Block

37

Windows and Layouts | IAT351 | February 1, 2008

Font Class

• Font objects are used to set the font for text on GUI components• Font Constructor

Font(String name, int style, int size)Examples:

Font myFont = new Font(“Arial”, Font.PLAIN, 12);Font myNewFont = new Font(“Courier”, Font.ITALIC+Font.BOLD,

14);• FontMetrics object is used to get information such as the exact

length, and width of a string, helpful for measuring its size in orderto display it in the right position

• Key Attributes: Leading, Ascent, Descent, Height

Windows and Layouts | IAT351 | February 1, 2008

Fontmetrics and Key Attributes

• Leading (“ledding”) Amount of space between lines of text.• Ascent: The height of a character from baseline to the top.• Descent: The distance from the baseline to the bottom of a

descending character, such as g, j, y• Height: The sum of the leading, ascent, and descent. i.e. Height = Leading + Ascent + Descent See the next slide for a diagram of these attributes

Page 38: Window systems, layouts and toolkits IAT351 · Windows and Layouts | IAT351 | February 1, 2008 Window Systems: a little history • The BitBlt algorithm Dan Ingalls, “Bit Block

38

Windows and Layouts | IAT351 | February 1, 2008

The FontMetrics Class

ByLeading

Ascent

DescentBaseline

Height

Windows and Layouts | IAT351 | February 1, 2008

getFontMetrics methods

public FontMetrics getFontMetrics(Font f) - returns the font metrics of the specified classpublic FontMetrics getFontMetrics(Font f) - returns the font metrics of the current fontpublic void paintMethod(Graphics g) then use: g.getFontMetrics(Font f); or g.getFontMetrics( );public int getAscent( )

public int getDescent( )

public int getLeading( )

public int getHeight( )

public int stringWidth(String str)

Page 39: Window systems, layouts and toolkits IAT351 · Windows and Layouts | IAT351 | February 1, 2008 Window Systems: a little history • The BitBlt algorithm Dan Ingalls, “Bit Block

39

Windows and Layouts | IAT351 | February 1, 2008

TestFontMetrics.java &MessagePanel.java// MessagePanel.java: Display a message on a JPanelimport java.awt.Font;import java.awt.FontMetrics;import java.awt.Dimension;import java.awt.Graphics;import javax.swing.JPanel;

public class MessagePanel extends JPanel{ private String message = "Welcome to Java"; // Message to display

Windows and Layouts | IAT351 | February 1, 2008

TestFontMetrics.java &MessagePanel.java // (x, y) coordinates where the message is displayed private int xCoordinate = 20; private int yCoordinate = 20;

// Indicating whether the message is displayed in the center private boolean centered; // true or false

// Font used to display message private Font font = new Font("SansSerif", Font.BOLD, 20);

Page 40: Window systems, layouts and toolkits IAT351 · Windows and Layouts | IAT351 | February 1, 2008 Window Systems: a little history • The BitBlt algorithm Dan Ingalls, “Bit Block

40

Windows and Layouts | IAT351 | February 1, 2008

TestFontMetrics.java &MessagePanel.javapublic MessagePanel( ) // Default constructor { repaint( ); // update the image } // Contructor with a message parameter public MessagePanel(String message) { this.message = message; repaint( ); // update the image } public String getMessage( ) // getter method { return message; }

Windows and Layouts | IAT351 | February 1, 2008

TestFontMetrics.java &MessagePanel.java public void setMessage(String message) // setter method { this.message = message; }

public int getXCoordinate( ) // getter method { return xCoordinate; }

public void setXCoordinate(int x) // setter method { this.xCoordinate = x; }

public int getYCoordinate( ) // getter method { return yCoordinate; }

Page 41: Window systems, layouts and toolkits IAT351 · Windows and Layouts | IAT351 | February 1, 2008 Window Systems: a little history • The BitBlt algorithm Dan Ingalls, “Bit Block

41

Windows and Layouts | IAT351 | February 1, 2008

TestFontMetrics.java &MessagePanel.javapublic void setYCoordinate(int y) // setter method { this.yCoordinate = y; }

public Font getFont() // getter method { return font; }

public void setFont(Font font) // setter method { this.font = font; }

public boolean isCentered( ) // return true or false { return centered; }

Windows and Layouts | IAT351 | February 1, 2008

TestFontMetrics.java &MessagePanel.java public void setCentered(boolean centered) { this.centered = centered; }

// Display the message at specified location public void paintComponent(Graphics g) { super.paintComponent(g); if (centered) { // Get font metrics for the font FontMetrics fm = g.getFontMetrics(font);

Page 42: Window systems, layouts and toolkits IAT351 · Windows and Layouts | IAT351 | February 1, 2008 Window Systems: a little history • The BitBlt algorithm Dan Ingalls, “Bit Block

42

Windows and Layouts | IAT351 | February 1, 2008

TestFontMetrics.java &MessagePanel.java// Find the center location to display int w = fm.stringWidth(message); // Get the string width int h = fm.getAscent(); // Get the string height xCoordinate = (getSize().width-w)/2; // Get center point yCoordinate = (getSize().height+h)/2; // Get center point } // Display the message g.drawString(message, xCoordinate, yCoordinate); }

Windows and Layouts | IAT351 | February 1, 2008

Drawing Geometric Figures in the Graphicsclass

• Drawing Lines• Drawing Rectangles• Drawing Ovals• Drawing Arcs• Drawing Polygons

Page 43: Window systems, layouts and toolkits IAT351 · Windows and Layouts | IAT351 | February 1, 2008 Window Systems: a little history • The BitBlt algorithm Dan Ingalls, “Bit Block

43

Windows and Layouts | IAT351 | February 1, 2008

Drawing Lines in the Graphics Class

// Draw a straight line from

// point (x1,y1) to point ( x2,y2)

drawLine(x1, y1, x2, y2);

Windows and Layouts | IAT351 | February 1, 2008

Drawing Rectangles in the GraphicsClass

• drawRect(x, y, w, h);

// x,y are starting coordinates

// w, h are width and height

// To draw a rectangle filled with color:

• fillRect(x, y, w, h);

Page 44: Window systems, layouts and toolkits IAT351 · Windows and Layouts | IAT351 | February 1, 2008 Window Systems: a little history • The BitBlt algorithm Dan Ingalls, “Bit Block

44

Windows and Layouts | IAT351 | February 1, 2008

Drawing Rounded Rectangles

• drawRoundRect(x, y, w, h, aw, ah);

// “aw” is the horizontal diameter of the

// arcs at the corner and “ah” is the

// vertical diameter of the arcs at the

// corner

• fillRoundRect(x, y, w, h, aw, ah);

// To fill a round rectangle with color, use the above method

Windows and Layouts | IAT351 | February 1, 2008

Drawing Ovals

• drawOval(x, y, w, h); // To draw an oval from starting point

// x,y with width ‘w’ and height ‘h’

• fillOval(x, y, w, h);

// To draw an oval filled with color

Page 45: Window systems, layouts and toolkits IAT351 · Windows and Layouts | IAT351 | February 1, 2008 Window Systems: a little history • The BitBlt algorithm Dan Ingalls, “Bit Block

45

Windows and Layouts | IAT351 | February 1, 2008

Drawing Arcs

• drawArc(x, y, w, h, angle1, angle2);

• fillArc(x, y, w, h, angle1, angle2);

// angle1 is starting angle; angle2 is spanning angle

(x, y)

w

hangle1

angle2

Windows and Layouts | IAT351 | February 1, 2008

Drawing Polygons

A polygon is a list of (x,y) coordinate pairs in which each pairdefines the vertex of a polygon, and two successive pairs are theendpoints of a line that is a side of the polygon.

The first and final (x,y) points are joined by a line segment thatcloses the polygon.

Page 46: Window systems, layouts and toolkits IAT351 · Windows and Layouts | IAT351 | February 1, 2008 Window Systems: a little history • The BitBlt algorithm Dan Ingalls, “Bit Block

46

Windows and Layouts | IAT351 | February 1, 2008

Drawing Polygons

Two methods for drawing polygons:

drawPolygon (x, y, n);

fillPolygon (x, y, n);

Parameters ‘x’ and ‘y’ are arrays representing x-coordinates and y- coordinates.

‘n’ is the number of points.

Windows and Layouts | IAT351 | February 1, 2008

Drawing Polygons: Example

int[] x = {40, 70, 60, 45, 20}; // x coordinatesint[] y = {20, 40, 80, 45, 60}; // y coordinates

g.drawPolygon(x, y, x.length);

g.fillPolygon(x, y, x.length);

See the Java program TestPolygon.java