Download presentation
Presentation is loading. Please wait.
Published byPierce Dorsey Modified over 9 years ago
1
1 Lecture 10 Graphical User Interfaces Instructors: Fu-Chiung Cheng ( 鄭福炯 ) Associate Professor Computer Science & Engineering Tatung Institute of Technology
2
1 Outline Interaction with a graphical user interface (GUI) Java’s GUIs: java.awt package We will focus on –GUI components –event-driven programming –containers and component hierarchies –layout managers
3
2 GUI Elements The key elements of a Java graphical user interface are: –GUI components: text fields and buttons are the screen elements that a user manipulates with the mouse and keyboard –layout managers: govern how the components appear on the screen –event processing: Events signal important user actions, like a mouse click
4
3 Event-Driven Programming Programs with GUIs must respond to events, generated by GUI components, that indicate that specific actions have occurred A special category of classes, called listeners, wait for events to occur A GUI program is composed of: –the code that presents the GUI to the user –the listeners that wait for events to occur –the specific code that is executed when events occur
5
4 Event-Driven Programming There is a listener interface defined for each event type Each listener interface contains the abstract methods required to respond to specific events A listener class implements a particular listener interface Listeners are "added" to a particular GUI component When a component generates an event, the method corresponding to that event is executed in the listener See Mimic.java
6
import java.applet.Applet; // Mimic.java import java.awt.*; import java.awt.event.*; public class Mimic extends Applet { Mimic_GUI gui = new Mimic_GUI (this); public void init() { gui.init(); } // method init public void update_label() { System.out.println("Action"); gui.update_label (gui.get_quote()); } // method set_uppercase } // class Mimic
7
import java.awt.event.*; class Mimic_Action_Listener implements ActionListener { private Mimic applet; public Mimic_Action_Listener (Mimic listening_applet) { applet = listening_applet; } // constructor Mimic_Action_Listener public void actionPerformed (ActionEvent event) { applet.update_label(); } // method actionPerformed } // class Mimic_Action_Listener
8
import java.awt.*; class Mimic_GUI { private Label label = new Label ("No news is good news."); private TextField quote = new TextField(20); private Mimic applet; private Mimic_Action_Listener listener; public Mimic_GUI (Mimic mimic_applet) { applet = mimic_applet; listener = new Mimic_Action_Listener (applet); } // constructor Mimic_GUI public void init() { applet.add(quote); applet.add(label); applet.resize(250,100); quote.addActionListener (listener); // associated listener } // method init public void update_label (String message) { label.setText (message); } // method update_label public String get_quote() { return quote.getText(); } // method get_quote } // class Mimic_GUI
9
5 The GUI Program Model Listeners Program- specific GUI Event effects Add listeners Handle events
10
6 Event Interfaces Multiple listeners can be added to a component Multiple components can be processed by the same listener Furthermore, one listener class can implement multiple listener interfaces Therefore, one class can listen for many types of events See Events.java
11
import java.awt.*; import java.awt.event.*; import java.applet.*; public class Events extends Applet { private TextArea log = new TextArea (10, 65); private int count = 0; private Label count_label = new Label("", Label.CENTER); private Universal_Listener listener = new Universal_Listener (log, count_label); public void init() { add ("North", new Label ("Event Logging", Label.CENTER)); add ("Center", log); add ("South", count_label); addComponentListener (listener); log.addFocusListener (listener); log.addKeyListener (listener); log.addMouseListener (listener); log.addMouseMotionListener (listener); setSize (500, 300); } } // class Events
12
class Universal_Listener implements ComponentListener, MouseMotionListener, MouseListener, KeyListener, FocusListener { private TextArea log; private Label count_label; private String count_text = "Number of Events: "; private int count = 0; public Universal_Listener (TextArea log, Label count_label) { this.log = log; this.count_label = count_label; } // constructor Universal_Listener private void log_event (AWTEvent event) { count++; count_label.setText (count_text + count); log.append (event.toString() + "\n"); } // method log_event
13
public void componentMoved (ComponentEvent event) { log_event (event); } // method componentMoved public void componentHidden (ComponentEvent event) { log_event (event); } // method componentHidden public void componentResized (ComponentEvent event) { log_event (event); } // method componentResized public void componentShown (ComponentEvent event) { log_event (event); } // method componentShown public void mouseDragged (MouseEvent event) { log_event (event); } // method mouseDragged public void mouseMoved (MouseEvent event) { log_event (event); } // method mouseMoved
14
public void mousePressed (MouseEvent event) { log_event (event); } // method mousePressed public void mouseReleased (MouseEvent event) { log_event (event); } // method mouseReleased public void mouseEntered (MouseEvent event) { log_event (event); } // method mouseEntered public void mouseExited (MouseEvent event) { log_event (event); } // method mouseExited public void mouseClicked (MouseEvent event) { log_event (event); } // method mouseClicked public void keyPressed (KeyEvent event) { log_event (event); } // method keyPressed
15
public void keyReleased (KeyEvent event) { log_event (event); } // method keyReleased public void keyTyped (KeyEvent event) { log_event (event); } // method keyTyped public void focusGained (FocusEvent event) { log_event (event); } // method focusGained public void focusLost (FocusEvent event) { log_event (event); } // method focusLost } // class Universal_Listener
16
7 Containers A container is a special category of GUI components that group other components All containers are components, but not all components are containers An applet is a container Therefore, buttons, text fields, and other components can be added to an applet to be displayed Each container has an associated layout manager to control the way components in it are displayed
17
8 Containers Some containers must be attached to another graphical surface: –panel –applet An applet is attached to a browser or appletviewer window Other containers can be moved independently: –window –frame –dialog
18
9 Containers Component Container Window Panel Dialog Frame Applet
19
10 Component Hierarchies A GUI is created when containers and other components are put together The relationships between these components form a component hierarchy For example, an applet can contain panels which contain other panels which contain buttons, etc. See Rings_Display.java Careful design of the component hierarchy is important for visually pleasing and consistent GUIs
20
11 GUI Components There are several GUI components that permit specific kinds of user interaction: –labels –text fields –text areas –lists –buttons –scrollbars See Quotes.java
21
12 Labels A label defines a line of text displayed on a GUI Labels are static in the sense that they cannot be selected or modified by the human user once added to a container A label is instantiated from the Label class The Label class contains several constructors and methods for setting up and modifying a label's content and alignment
22
13 Text Fields and Text Areas A text field displays a single line of text in a GUI It can be made editable, and provide a means to get input from the user A text area is similar, but displays multiple lines of text They are defined by the TextField and TextArea classes A text area automatically has scrollbars on its bottom and right sides See Fahrenheit.java
23
import java.applet.Applet; import java.awt.*; import java.awt.event.*; public class Fahrenheit extends Applet { private Label title = new Label ("Fahrenheit to Celcius Converter"); private Label question = new Label ("Enter Fahrenheit:"); private Label answer = new Label ("Temperature in Celcius:"); private TextField fahrenheit = new TextField (5); private Label celcius = new Label ("N/A"); private TextArea log = new TextArea (5, 20); private Fahrenheit_Listener listener = new Fahrenheit_Listener (this); public void init() { fahrenheit.addActionListener (listener); log.setEditable (false); add (title); add (question); add (fahrenheit); add (answer); add (celcius); add (log); resize (200,200); } // method init
24
public void convert() { int fahrenheit_temperature, celcius_temperature; String text = fahrenheit.getText(); fahrenheit_temperature = Integer.parseInt (text); celcius_temperature = (fahrenheit_temperature-32)*5/9; celcius.setText (Integer.toString (celcius_temperature)); log.append (text+" converts to "+celcius.getText() + "\n"); } // method convert } // class Fahrenheit class Fahrenheit_Listener implements ActionListener { private Fahrenheit applet; public Fahrenheit_Listener (Fahrenheit listening_applet) { applet = listening_applet; } // constructor Fahrenheit_Listener public void actionPerformed(ActionEvent action) { applet.convert(); } // method actionPerformed } // class Fahrenheit_Listener
25
14 Lists A list in Java GUI is used to display a list selectable strings A list component can contain any number of strings and may allow multiple selections The size of the list is specified by the number of visible rows or strings within it A scrollbar will automatically appear on the right side of a list if the number of items exceed the visible area A list is defined by the List class
26
15 Buttons The java.awt package supports four distinct types of buttons: –Push buttons –Choice Buttons –Checkbox buttons –Radio buttons Each button type serves a particular purpose
27
16 Push Button A push button is a single button which can be created with or without a label A system is usually designed such that when a push button is pressed, a particular action occurs It is defined by the Button class
28
17 Choice button A choice button is a single button which displays a list of choices when pushed The user can then scroll through and choose the appropriate option The current choice is displayed next to the choice button It is defined by the Choice class
29
18 Checkbox button A checkbox button can be toggled on or off A set of checkbox buttons are often used to define a set of options as a group, though one can be used by itself If used in a group, more than one option can be chosen at any one time Defined by the Checkbox class
30
19 Radio buttons A radio button, like a checkbox button, is toggled on or off Radio buttons must be grouped into a set, and only one button can be selected When one button of a group is selected, the currently selected button in that group is automatically reset Good for select a set of mutually exclusive options Radio button sets are defined by the Checkbox and CheckboxGroup classes
31
20 Scrollbars A scrollbar is a slider that indicates a relative position or quantity They are automatic on text areas and list components, but can be used independently The position of the slider in the range corresponds to a particular numeric value in a range associated with the scrollbar A scrollbar is defined by the Scrollbar class See Zoom.java
32
import java.applet.*; import java.awt.*; import java.awt.event.*; public class Zoom extends Applet { private final int SIZE = 300; private Scrollbar bar = new Scrollbar(Scrollbar.HORIZONTAL, 10, 64, 10, SIZE); private Zoom_Listener listener = new Zoom_Listener (this); private int current_size = 10; private Image picture; public void init() { setLayout (new BorderLayout()); setBackground (Color.white); bar.addAdjustmentListener (listener); picture = getImage (getDocumentBase(), "owl.gif"); add (bar, "South"); setSize (SIZE, SIZE); setVisible (true); } // method init
33
public void zoom_image (int size) { current_size = size; repaint(); } // method zoom_image public void paint (Graphics page) { page.drawImage (picture, SIZE/2-current_size/2, SIZE/2-current_size/2, current_size, current_size, this); } // method draw } // class Zoom class Zoom_Listener implements AdjustmentListener { private Zoom applet; public Zoom_Listener (Zoom zoom_applet) { applet = zoom_applet; } // constructor Zoom_Listener public void adjustmentValueChanged (AdjustmentEvent event) { applet.zoom_image (event.getValue()); } // method adjustmentValueChanged } // class Zoom_Listner
34
21 Layout Managers Five predefined layout managers AWT package: –flow layout –border layout –card layout –grid layout –grid bag layout Each container has a particular layout manager associated with it by default
35
22 Flow Layout Components are placed in a row from left to right in the order in which they are added A new row is started when no more components can fit in the current row The components are centered in each row by default The programmer can specify the size of both the vertical and horizontal gaps between the components Flow layout is the default layout for panels and applets See Flow.java
36
23 Grid Layout Components are placed in a grid with a user-specified number of columns and rows Each component occupies exactly one grid cell Grid cells are filled left to right and top to bottom All cells in the grid are the same size See Grid.java
37
import java.applet.Applet; import java.awt.*; public class Flow extends Applet { private Button button1 = new Button ("I"); private Button button2 = new Button ("think"); private Button button3 = new Button ("therefore"); private Button button4 = new Button ("I"); private Button button5 = new Button ("am"); public void init() { setLayout (new FlowLayout()); add (button1); add (button2); add (button3); add (button4); add (button5); setVisible(true); } // method init } // class Flow
38
24 Border Layout Defines five locations each of which a component or components can be added –North, South, East, West, and Center The programmer specifies the area in which a component should appear The relative dimensions of the areas are governed by the size of the components added to them See Border.java
39
import java.applet.Applet; import java.awt.*; public class Border extends Applet { private Button button1 = new Button ("I"); private Button button2 = new Button ("think"); private Button button3 = new Button ("therefore"); private Button button4 = new Button ("I"); private Button button5 = new Button ("am"); public void init() { setLayout (new BorderLayout()); add (button1, "North"); add (button2, "South"); add (button3, "East"); add (button4, "West"); add (button5, "Center"); setVisible(true); } // method init } // class Border
40
25 Border Layout North South West East Center
41
26 Card Layout Components governed by a card layout are "stacked" such that only one component is displayed on the screen at any one time Components are ordered according to the order in which they were added to the container Methods control which component is currently visible in the container See Card.java
42
import java.applet.Applet; import java.awt.*; public class Card extends Applet { private Button button1 = new Button ("I"); private Button button2 = new Button ("think"); private Button button3 = new Button ("therefore"); private Button button4 = new Button ("I"); private Button button5 = new Button ("am"); private CardLayout layout = new CardLayout(); public void init() { setLayout (layout); add (button1, "One"); add (button2, "Two"); add (button3, "Three"); add (button4, "Four"); add (button5, "Five"); setVisible(true); } // method init public void start() { for (int cards = 1; cards < 50; cards++) { layout.next(this); for (int pause = 1; pause < 400000; pause++); } } } // class Card
43
27 Grid Bag Layout Designed as a two-dimensional grid of columns and rows However, not all cells in the grid are the same size Components may span multiple columns and rows Each component in a grid bag layout is associated with a set of constraints, defined by the GridBagConstraints class A grid bag layout is the most versatile, and most complex, of the predefined layout managers See Grid_Bag.java
44
import java.applet.Applet; import java.awt.*; public class Grid extends Applet { private Button button1 = new Button ("I"); private Button button2 = new Button ("think"); private Button button3 = new Button ("therefore"); private Button button4 = new Button ("I"); private Button button5 = new Button ("am"); public void init() { setLayout (new GridLayout(2,3)); add (button1); add (button2); add (button3); add (button4); add (button5); setVisible(true); } // method init } // class Grid
45
import java.applet.Applet; import java.awt.*; public class Grid_Bag extends Applet { private Button button1 = new Button ("I"); private Button button2 = new Button ("think"); private Button button3 = new Button ("therefore"); private Button button4 = new Button ("I"); private Button button5 = new Button ("am"); private GridBagLayout gridbag = new GridBagLayout(); private void first_row (Button button) { GridBagConstraints constraints=new GridBagConstraints(); constraints.gridwidth = GridBagConstraints.REMAINDER; constraints.anchor = GridBagConstraints.WEST; gridbag.setConstraints (button, constraints); add (button); } // method first_row
46
private void second_row (Button button1, Button button2) { GridBagConstraints constraints = new GridBagConstraints(); constraints.gridwidth = 8; constraints.fill = GridBagConstraints.HORIZONTAL; constraints.weightx = 1.0; gridbag.setConstraints (button1, constraints); add (button1); constraints = new GridBagConstraints(); constraints.gridwidth = GridBagConstraints.REMAINDER; constraints.fill = GridBagConstraints.VERTICAL; constraints.weighty = 1.0; gridbag.setConstraints (button2, constraints); add (button2); } // method second_row
47
private void third_row (Button button) { GridBagConstraints constraints=new GridBagConstraints(); constraints.gridwidth = GridBagConstraints.REMAINDER; constraints.fill = GridBagConstraints.BOTH; constraints.weighty = 1.0; gridbag.setConstraints (button, constraints); add (button); } // method third_row private void forth_row (Button button) { GridBagConstraints constraints=new GridBagConstraints(); constraints.gridwidth = GridBagConstraints.REMAINDER; gridbag.setConstraints (button, constraints); add (button); } // method forth_row public void init() { setLayout(gridbag); first_row (button1); second_row (button2, button3); third_row (button4); forth_row (button5); setVisible(true); } } // class Grid_Bag
48
28 GUI Design Careful design of a graphical user interface is key to a viable software system To the user, the user interface is the system For each situation, consider which components are best suited and how they should best be arranged See Quotes.java
49
import java.applet.Applet; import java.awt.*; import java.awt.event.*; public class Quotes extends Applet { String[] text = {"Take my wife, please.", "We move our legs ourselves.", "Measure twice, cut once."}; Label quote = new Label (text[0], Label.CENTER); final public static int UPPERCASE = 1; final public static int LOWERCASE = 2; final public static int FONT = 3; final public static int COMEDY = 4; final public static int PHILOSOPHY = 5; final public static int CARPENTRY = 6; final public static int BOLD = 7; final public static int ITALIC = 8; Quote_GUI gui = new Quote_GUI (this); public void init() { quote.setFont (new Font ("Times", Font.PLAIN, 12)); gui.init (quote); } // method init
50
public void set_uppercase() { quote.setText (quote.getText().toUpperCase()); } // method set_uppercase public void set_lowercase() { quote.setText (quote.getText().toLowerCase()); } // method set_lowercase public void set_comedy() { quote.setText (text[0]); } // method set_comedy public void set_philosophy() { quote.setText (text[1]); } // method set_philosophy public void set_carpentry() { quote.setText (text[2]); } // method set_carpentry public void set_font (String font) { quote.setFont(new Font(font,quote.getFont().getStyle(),12)); } // method set_font
51
public void set_italics (boolean on) { Font font = quote.getFont(); int style = font.getStyle(); if (on) // Turn italic on or off if (! font.isItalic()) style += Font.ITALIC; else if (font.isItalic()) style -= Font.ITALIC; quote.setFont (new Font (font.getName(), style, 12)); } // method set_italics public void set_bold (boolean on) { Font font = quote.getFont(); int style = font.getStyle(); if (on) // Turn bold on or off if (! font.isBold()) style += Font.BOLD; else if (font.isBold()) style -= Font.BOLD; quote.setFont (new Font (font.getName(), style, 12)); } } // class Quotes
52
class Quote_GUI { private Quotes applet; private Panel letters = new Panel(); private Panel domain = new Panel(); private Panel style = new Panel(); private Button uppercase = new Button ("Uppercase"); private Button lowercase = new Button ("Lowercase"); private Choice font_choice = new Choice(); private CheckboxGroup topic = new CheckboxGroup(); private Checkbox comedy = new Checkbox ("Comedy", topic, true); private Checkbox philosophy = new Checkbox ("Philosophy", topic, false); private Checkbox carpentry = new Checkbox ("Carpentry", topic, false); private Checkbox bold = new Checkbox ("Bold"); private Checkbox italic = new Checkbox ("Italic");
53
private Quote_Action_Listener uppercase_listener; private Quote_Action_Listener lowercase_listener; private Quote_Item_Listener bold_listener; private Quote_Item_Listener italic_listener; private Quote_Item_Listener font_listener; private Quote_Item_Listener comedy_listener; private Quote_Item_Listener philosophy_listener; private Quote_Item_Listener carpentry_listener;
54
public Quote_GUI (Quotes quote_applet) { applet = quote_applet; uppercase_listener = new Quote_Action_Listener (applet, Quotes.UPPERCASE); lowercase_listener = new Quote_Action_Listener (applet, Quotes.LOWERCASE); bold_listener = new Quote_Item_Listener (applet, Quotes.BOLD); italic_listener = new Quote_Item_Listener (applet, Quotes.ITALIC); font_listener = new Quote_Item_Listener (applet, Quotes.FONT); comedy_listener = new Quote_Item_Listener (applet, Quotes.COMEDY); philosophy_listener = new Quote_Item_Listener (applet, Quotes.PHILOSOPHY); carpentry_listener = new Quote_Item_Listener (applet, Quotes.CARPENTRY); } // constructor Quote_GUI
55
public void init (Label quote) { // setup the component hierarchy font_choice.addItem ("Courier"); font_choice.addItem ("Times"); font_choice.addItem ("Helvetica"); letters.setLayout (new GridLayout (4,1,3,3)); letters.add (uppercase); letters.add (lowercase); letters.add (font_choice); domain.setLayout (new GridLayout (4,1)); domain.add (comedy); domain.add (philosophy); domain.add (carpentry); style.setLayout (new GridLayout (4,1)); style.add (bold); style.add (italic)
56
applet.setLayout (new BorderLayout(10,2)); applet.add ("North", quote); applet.add ("West", letters); applet.add ("Center", domain); applet.add ("East", style); applet.resize (260,150); // Add all associated listeners uppercase.addActionListener (uppercase_listener); lowercase.addActionListener (lowercase_listener); font_choice.addItemListener (font_listener); comedy.addItemListener (comedy_listener); philosophy.addItemListener (philosophy_listener); carpentry.addItemListener (carpentry_listener); bold.addItemListener (bold_listener); italic.addItemListener (italic_listener); } // method init } // class Quote_GUI
57
class Quote_Item_Listener implements ItemListener { private Quotes applet; private int command; public Quote_Item_Listener (Quotes listening_applet, int listening_command) { applet = listening_applet; command = listening_command; } // constructor Quote_Item_Listener public void itemStateChanged (ItemEvent event) { switch (command) { case Quotes.FONT: applet.set_font ((String)(event.getItem())); break; case Quotes.COMEDY: applet.set_comedy(); break; case Quotes.PHILOSOPHY: applet.set_philosophy();break; case Quotes.CARPENTRY:applet.set_carpentry(); break; case Quotes.BOLD: applet.set_bold (event.getStateChange() == ItemEvent.SELECTED); break; case Quotes.ITALIC: applet.set_italics (event.getStateChange() == ItemEvent.SELECTED);break; default: System.out.println("Illegal Item "+event.toString()); } } } // class Quote_Item_Listener
58
class Quote_Action_Listener implements ActionListener { private Quotes applet; private int command; public Quote_Action_Listener (Quotes listening_applet, int listening_command) { applet = listening_applet; command = listening_command; } // constructor Quote_Action_Listener public void actionPerformed (ActionEvent event) { switch (command) { case Quotes.UPPERCASE: applet.set_uppercase(); break; case Quotes.LOWERCASE: applet.set_lowercase(); break; default: System.out.println ("Illegal Action " + event.toString()); } } // method actionPerformed } // class Quote_Action_Listener
59
Conclusion
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.