Title: GUI Part 1:components and layout managers
1GUI Part 1 components and layout managers
Most, if not all, GUI systems and tookits are
designed to be event driven, meaning that the
main flow of your program is not sequential from
beginning to end. If you ve never done GUI
programming, this is one of the trkiest paradigm
shift - Robin Dunn, speaking on GUI programming
at OSCON2004
2Background Event Driven Programming
- All previous programs have been of a linear
nature - Prompt user
- Get response
- Do something
- Events happen in a pre-predefined sequence
- Event driven programming
- build GUI
- GUI is one of the most common use for
event-driven programming - react to actions (events) from user
- update state and interface
- Reacts to arbitrary sequences of events during
execution
3Event driven GUI programming
- A GUI combines three functions input, output,
and data handling - All processing happens as reactions to the
interactive manipulation of visual components. - Buttons, menus,
- Code is executed when events are generated by
user actions - such as mouse movements, pressing buttons,
- Hollywood principle Dont call us, we will call
you - You implement the interfaces, you get registered.
You get called when the time is right.
4GUIs an Example
5Implementation in Java components, events, and
listeners
- A component is an object that defines a screen
element such as a push button, text field, scroll
bar, menu, etc. - A container is a special type of component used
to hold and organize other components. - An event is an object that represents some
occurrence. Often events correspond to user
actions such as pressing a mouse button,
selecting an item from a menu, or typing in a
text field. - The event source is the GUI component in which
the event occurred. - A listener is an object that is waiting for an
event to occur and can respond in some way when
it does. - The programmer must establish the relationships
among the listener, the event it listens for, and
the component that will generate the event. This
includes two tasks registering the event
listener and implementing the event handler. Â
6Implementation in Java AWT vs Swing
- Java provides two sets of GUI components
- AWT Abstract Windowing Toolkit
- AWT components are tied directly to the local
platforms GUI capabilities. - Heavyweight, platform dependent, and inflexible
- Swing is implemented entirely in the Java
programming language, and is based on the JDK 1.1
Lightweight UI Framework. - Have platform-independent look-and-feel
- In general
- AWT components are appropriate for simple applet
development or development that targets a
specific platform - For most any other Java GUI development, use
Swing components. - Hint Whether you choose to use Swing or AWT for
your Java program development, you should avoid
mixing the two - A brief comparison of Swing and the AWT when used
for GUI developement
7Swing Hierarchy
8Swing components examples
JButton
JCheckBox
JList
JComboBox
JRadioButton
JMenu
JFileChooser
A visual guide to Swing components
9Swing containers
- While a GUI component is a visible object in a
graphical user interface, a GUI container is an
area which components can be placed. - Swing provides three generally useful top-level
container classes JFrame, JDialog, and JApplet. - JFrame implements a single main frame
- JDialog implements a secondary window
- JApplet an applet display area
10Containment Hierarchy
- To appear onscreen, every GUI component must be
part of a containment hierarchy. A containment
hierarchy is a tree of components that has a
top-level container as its root - Each GUI component can be contained only once
- You can optionally add a menu bar to a top-level
container
A guide to use top level containers in Swing
11How to make Frames (1)?
- A Frame is a top-level window with a title and a
border - The following code shows how to create and set up
a frame.
//1. Create the frame. JFrame frame new
JFrame("FrameDemo") //2. Optional What happens
when the frame closes? frame.setDefaultCloseOperat
ion(JFrame.EXIT_ON_CLOSE) //3. Create
components and put them in the frame. //...create
emptyLabel... frame.getContentPane().add(emptyLabe
l, BorderLayout.CENTER) //4. Size the
frame. frame.pack() //5. Show it.
frame.setVisible(true)
12How to make frames (2)?
- A JFrame contains a JRootPane as its only child.
- The content pane provided by the root pane
should, as a rule, contain all the non-menu
components displayed by the JFrame. - Content panes use BorderLayout by default.
- Starting from J2SE5.0, As a convenience, the add
method and its variants, remove and setLayout
have been overridden to forward to the
contentPane as necessary. This means you can
write frame.add(child)and the child will be
added to the contentPane. - jFrame.add is equivalent to jFrame.getContentPane
().add(). - Note that only these three methods do this. This
means that getLayout() will not return the layout
set with setLayout().
13How to make dialogs (1)?
- A Dialog window is an independent subwindow meant
to carry temporary notice - JOptionPane
- JProgressMonitor
- JOptionPane
- JOptionPane makes it easy to pop up a standard
dialog box that prompts users for a value or
informs them of something - Main methods
14How to make dialogs (2)?
- Examples (See how to make dialogs)
- Examples
- Show an error dialog that displays the message,
'alert' - JOptionPane.showMessageDialog(null, "alert",
"alert", JOptionPane.ERROR_MESSAGE)
- Show a dialog asking the user to select a String
- Object possibleValues "First", "Second",
"Third" Object selectedValue
JOptionPane.showInputDialog(null, "Choose one",
"Input",JOptionPane.INFORMATION_MESSAGE, null,
possibleValues, possibleValues0)
15How to Use File Choosers (1)?
- File choosers provide a GUI for navigating the
file system, and then either choosing a file or
directory from a list, or entering the name of a
file or directory.
16How to Use File Choosers (2)?
- Several steps
- To Create an Open File Chooser
- JFileChooser fc new JFileChooser()
- To display a file chooser
- int returnVal fc.showOpenDialog(owner) //
button labeled "Open - int returnVal fc.showSaveDialog(owner) //
button labeled "Save" - Checking the return value
- if (returnVal JFileChooser.APPROVE_OPTION)
- Getting the selected file or directory
- File file fc.getSelectedFile()
17How to use JPanel?
- A JPanel is an empty area that can be used either
to - Layout other components, including other panels.
See below. - Draw graphics on
- The default layout FlowLayout
- Use a JPanel to layout other components
1. Declare and create the JPanel For example,
JPanel p new JPanel() 2. Set the layout and
other characteristics For example,
p.setLayout(new BorderLayout())
p.setPreferredSize(new Dimension(200, 100))
p.setBackground(Color.blue) 3. Add components
Use add(...) to add components to a panel. For
example, p.add(plusButton, BorderLayout.NORTH)
p.add(minusButton, BorderLayout.SOUTH)
18How to Use Menu?
- A menu is a way to arrange buttons.
- Menus are unique in that, by convention, they
aren't placed with the other components in the
UI. Instead, a menu usually appears either in a
menu bar or as a popup menu. - A menu bar can be added to the top of a top-level
container, eg, JFrame, JApplet, or JDialog. Note
that a menu bar can not be added to JPanel. - Menu-related components
- a menu bar,
- menus,
- menu items,
- radio button menu items,
- check box menu items,
- separators
19How to use Buttons, ComboBoxes, and Radio Buttons?
- General considerations
- Declaring and creating it
- JButton okButton new JButton(OK)
- JCheckBox ignoreCase new JCheckBox("Ignore
Case", true) - Adding a listener
- okButton.addActionListener(listener)
- ignoreCase.addItemListener( this)
- Adding to a container
- frame.getContentPane( ).add(okButton)
- frame.getContentPane( ).add(ignoreCase)
-
20Steps to create a GUI in Java (1)
- Extending the top-level containers by creating a
new class
import javax.swing. public class SimpleFrame
extends JFrame public static void main (String
args) JFrame frame new SimpleFrame ()
... frame.pack() frame.setVisible(true)
- Adding components to a container
21Steps to create a GUI in Java (2)
- Adding components to a container
- Create and initialize a component.
- Add it to the container by invoking the add()
method on the container object.
JLabel label new JLabel("Hello World")
frame.getContentPane().add(label)
A guild to use Swing components
- Note As a convenience, the add method and its
variants, remove and setLayout have been
overridden to forward to the contentPane as
necessary. This means you can write
frame.add(label)and the label will be added to
the contentPane. - Arrange/layout components
- Handle the events generated by the components
22Layout Managers
- The purpose of using layout managers
- A layout manager is an object that implements the
LayoutManager interface - It determines the size and position of the
components within a container. - Although components can provide size and
alignment hints, a container's layout manager has
the final say on the size and position of the
components within the container
23Types of Layout Managers
- FlowLayout
- BorderLayout
- BoxLayout
- CardLayout
- GridLayout
- GridBagLayout
- GroupLayout
- SpringLayout
- Layout mangers provided by third parties
24FlowLayout
- FlowLayout
- The default layout manager for every JPanel.
- It simply lays out components in a single row,
starting a new row if its container is not
sufficiently wide - For further details, see How to Use FlowLayout.
-
public void init() Button button1 new
Button("Ok") Button button2 new
Button("Open") Button button3 new
Button("Close") add(button1) add(button2)
add(button3)
25BorderLayout
- BorderLayout
- The default layout manager for every content pane
- A BorderLayout places components in up to five
areas north, south, west, east, and center. - All extra space is placed in the center area.
- Often a container uses only one or two of the
areas just the center, or the center and the
bottom - For further details, see How to Use BorderLayout
26BorderLayout Examples
- When adding a component to a container with a
border layout, use one of the following five
constants NORTH, SOUTH, EAST, WEST, and CENTER. -
- The absence of a string specification is
interpreted the same as the constant CENTER - Not all regions are required
- If nothing has been added to a region, the
neighboring regions expand to fill that space
JPanel p new JPanel() p.setLayout(new
BorderLayout()) p.add(new Button("Okay"),
BorderLayout.SOUTH)
p.add(new TextArea()) // Same as p.add(new
TextArea(), BorderLayout.CENTER)
27GridLayout
- A GridLayout object places components in a grid
of cells whose dimension (in terms of number of
rows and columns)Â can be specified by the user. - Each component takes all the available space
within its cell, and each cell is exactly the
same size. - If the window is resized, the GridLayout object
changes the cell size so that the cells are as
large as possible, given the space available to
the container. - When both the number of rows and the number of
columns have been set to non-zero values,the
number of columns specified is ignored. - Specifying the number of columns affects the
layout only when the number of rows is set to
zero.
28GridLayout Examples
- To Create a GridLayout
- p.setLayout(new GridLayout()) // One row.
Columns expand. p.setLayout(new GridLayout(rows,
cols)) - p.setLayout(new GridLayout(rows, cols, hgap,
vgap)) - To add Components to a GridLayout
- Use the .add(. . .) method to add components to a
container with a GridLayout. - You can not use the row and column to tell where
to add the components -- add them in starting at
the top left and going across the row first. - Empty Cells
- There is no way to leave a cell empty in a grid
layout. - The easiest way to do this is to put an empty
label in any cell you want to skip. - p.add(new JLabel(""))
29Tips on Choosing a Layout Manager
- Have a look at a visual guide to layout managers
- In Java, the only containers whose layout
managers you need to worry about are JPanels and
content panes. - Usually, containers are nested one into the
other, in order to build complex GUIs. - Nesting panels (ie panels within panels) allows
for more complex layouts to be constructed from
the simpler layouts - Several scenarios
- You need to display a component in as much space
as it can get. - You need to display a few components in a compact
row at their natural size. - You need to display a few components of the same
size in rows and columns -