Upload
gavin-blake
View
233
Download
2
Embed Size (px)
Citation preview
CS1054: Lecture 21
- Graphical User Interface
Graphical User Interfaces vs. Text User Interface
Three steps to GUI Programming
What kind of elements can we show on screen? Components
How do we arrange those elements? Layout
How do we react to user input? Event Handlers
AWT vs SWING
Java has two GUI libraries – AWT and Swing
Swing later and much improved than AWT
Equivalent classes in Swing can be identified by a J at the start of class name.
Top level Window
In control of Operating System’s window management
Java word – Frames Swing calls - JFrame
JFrame Windows
Title bar
Menu bar
Content pane
Adding Simple Components
JLabel
frame.pack( );frame.setVisible (true);
Adding Menus
JMenuBar JMenu JMenuItem
Creating Menubars – 3 stepsJMenuBar menubar = new JMenuBar ( );frame.setJMenuBar ( menubar );
JMenu fileMenu = new JMenu ( “File”);menubar.add (fileMenu);
JMenuItem openItem = new JMenuItem (“Open”);fileMenu.add (openItem);
JMenuItem quitItem = new JMenuItem (“Quit”);fileMenu.add (quitItem);
Event Handling
ActionEvent MouseEvent WindowEvent
To receive events
1. import java.awt.event.*;2. To class header ActionListener interface3. public void actionPerformed
(ActionEvent event)4. The objects must call addActionListener
( ) to register as a listener
Add ActionListener
public class ImageViewer implements ActionListener public void actionPerformed (ActionEvent event) {
System.out.println ("Item: " + event.getActionCommand ( )); }
openItem.addActionListener( this); quitItem.addActionListener( this);
Layout Managers
- Arrange components on a screen.- Each container has a Layout
Manager associated with it.- The Layout Manager takes care of
arranging components within that container
Layout Managers
http://java.sun.com/docs/books/tutorial/uiswing/layout/visual.html- FlowLayout- BorderLayout- GridLayout
MouseListener Demo
http://java.sun.com/j2se/1.4.2/docs/api/java/awt/event/MouseListener.html