Title: Chapter 7 Improving the User Interface
1Chapter 7Improving the User Interface
2Objectives
- Construct a query-driven terminal interface.
- Construct a menu-driven terminal interface.
- Construct a graphical user interface.
- Format text, including numbers, for output.
- Handle number format exceptions during input.
3Vocabulary
- Menu-driven program
- Query-controlled input
47.1 A Thermometer Class
57.2 Repeating Sets of Inputs
- Chapter 4 presented count-controlled and
sentinel-controlled input. - Query-controlled input Before each set of inputs
after the first, the program asks the user if
there are more inputs. The user answers with y
(yes) or n (no).
67.2 Repeating Sets of Inputs
Figure 7-1 Interface for a query-controlled
temperature conversion program
77.2 Repeating Sets of Inputs
- Program implemented by two classes
- Interface class (view class)
- Thermometer class
87.2 Repeating Sets of Inputs
- Pseudocode for interface (view) class
97.2 Example 7.1 ConvertWithQuery.java
107.3 Menu-Driven Conversion Program
- Menu-driven programs Display list of options
user selects one, then - Program prompts for additional inputs related to
that option and performs computations. - Menu is displayed again.
117.3 Menu-Driven Conversion Program
Figure 7-2 Interface for a menu-driven version
of the temperature conversion program
127.3 Menu-Driven Pseudocode
137.4 Formatted Output with printf and format
- Java 5.0 includes method printf for formatting
output. There are two parameters for a printf
statement - A format string that contains literal string
information and formatting information using
format specifiers. - A list of variables or expressions to be
formatted. There should be one variable or
expression for every format specifier in the
format string. - General form of printf
147.4 Format Specifiers with printf
- The format string consists of one or more format
specifiers. Each format specifier begins with a
character and ends with a letter that
indicates the format type. Here is an example of
using printf in a terminal program - double dollars 25
- double tax dollars 0.125
- System.out.printf(Income .2fn, dollars)
- System.out.printf(Tax owed .2fn, tax)
- Or in one line of code
- System.out.printf(Income .2fnTax owed
.2fn, dollars, tax) -
157.4 Format Specifiers with String.format
- Since printf only works with terminal programs,
here is an example of using String.format in a
GUI program. We might want to format columns in
a JTextArea GUI component. You will learn about
JTextArea components in section 6. Look at how we
substitute String.format for System.out.prinf and
store the formatted string in a String variable. - double dollars 25
- double tax dollars 0.125
- String s1 String.format(Income .2fn,
dollars) - String s2 String.format(Tax owed .2fn,
tax)
167.4 Format Types
Table 7-1 Commonly used format types
177.4 n and
- Symbol n embeds an new-line character in a
format string. - Symbol produces literal '' character.
- When compiler sees a format specifier, it
attempts to match that specifier to an expression
following the string. - Must match in type and position
187.4 Formatted Output with printf and format
- printf can justify text and produce tabular
output and use Format flags to support
justification and other styles.
The most important format flags are the first two.
197.4 Formatted Output with printf and format
Figure 7-3 Table of sales figures shown with and
without formatting
207.4 Formatted Output with printf and format
- To output data in formatted columns
- Establish the width of each field.
- Choose appropriate format flags and format
specifiers to use with printf. - The width of a field that contains a double
appears before the decimal point in the format
specifier f.
217.4 Formatted Output with printf and format
Table 7-3 Some example format strings and their
outputs
227.4 Formatted Output with printf and format
Note the ,12.2f in the last printf statement
above, the use of the decimal separator flag ,
(comma) to place commas every 3 decimal places in
the value contained in salary. Run the
DisplayTable_7_3.java demo program and view the
output to see the commas in the numbers.
237.4 Formatted Output with printf and format
- Formatting with String.format
- Can be used to build a formatted string
- Same syntax as printf
- Difference is that resulting string is not
displayed on the console - Using String.format to build a string can be very
valuable when outputting data to a TextArea in a
GUI program. You use printf statements only with
TerminalIO programs!
247.5 Handling Number Format Exceptions During
Input
- To this point, if data input is invalid, a
program will throw an exception and display an
error message in the terminal window and halt the
program. (An applet program may just do nothing
in response to invalid data.) - What we really want to happen is for a program to
identify invalid data and output an error
message, but then continue to run the program
without halting it.
257.5 Handling Number Format Exceptions During
Input
- The preceeding situation usually occurs when we
are asking for numeric input and characters other
than decimal digits are entered from the
keyboard. - Methods like nextInt() and nextDouble() actually
implicitly (behind the scene) parse the data
input from the keyboard when using a Scanner
object. If the data is not numeric, then an
exception will be thrown and the program will be
halted unless nextInt and nextDouble are imbedded
in a try-catch statement.
267.5 Handling Number Format Exceptions During
Input
- In GUI programs, we actually explicitly perform
the parsing of input with lines of code that use
parseInt() and parseDouble(), since a user would
not be able to see any exception errors in a
terminal window. - To allow a GUI or terminal program to continue,
we can place our lines that parse the input
inside a try-catch statement as stated before.
277.5 Try-Catch Statements
- Java provides a try-catch statement to allow us
to process data and other situations and keep the
program from being halted if invalid data is
entered or logic errors try to occur. - The try-catch construct allows exceptions to be
caught and handled appropriately.
287.5 Handling Number Format Exceptions During
Input
- Statements within a try clause are executed until
an exception is thrown or all statements are
executed. If an exception is thrown, execution
is immediately sent to the catch clause, skipping
the remainder of any code in the try clause. - try
- String input fahrField.getText() //get
the input from a GUI field - double fahr Double.parseDouble(input)
- // other code
- catch (Exception e)
- System.out.println(Bad Number Format!)
297.5 Handling Number Format Exceptions During
Input
All input from a GUI text field is of type
string, even values like 17 or 34.5678. The
methods parseInt and parseDouble convert input to
an int or double value unless a value like the
string asdf is entered. asdf cannot be parsed
to an int or double, so the methods parseInt or
parseDouble would throw an exception or with the
try-catch statement immediately execute the catch
clause. try String input
fahrField.getText() //get the input from a GUI
field double fahr Double.parseDouble(input)
// other code catch (Exception e)
System.out.println(Bad Number Format!)
307.5 Handling Number Format Exceptions During
Input
- If no statement throws an exception within the
try clause, the catch clause is skipped. - Many types of exceptions can be thrown.
- Catching an Exception object will catch any of
them. You could choose to use an
ArithmeticException if you wanted to output an
error if a program tries to divide by zero.
317.6 Graphics and GUIs
- GUIs based on pop-up dialogs can be limiting and
tedious to use if a lot of input needs to be
entered. - A better GUI presents the user with entry fields
(JTextFields) for many data values simultaneously
and then with the click of a button or use of a
drop-down list, the program can process its data.
327.6 Model/View/Controller Pattern
Figure 7-4 Interface for the GUI-based
temperature conversion program
337.6 Model/View/Controller Pattern
- The model/view/controller pattern is used by most
programmers as a way to consistently divide the
responsibility of different aspects of an
application between different classes in an
organized manner. - Model The data that the program uses and the
operations that can be performed on that data.
In this program, the Thermometer class serves as
the model. - View What the user of the program interacts
with. In this program, the GUIWindow class is the
view. - Controller Coordinates model and view classes by
passing messages and data between them - Listener classes. In this program, the private
inner class FahrenheitListener is the controller. - Can be attached to widgets in the view class
347.6 Model/View/Controller Pattern
- When a controller class receives an event from a
view class, it sends a message to a model class.
In the ConvertWithGUI program, the
FahrenheitListener class receives an event from
the GUIWindow class and then sends a message to
the Thermometer class - The ConvertWithGUI frame program uses a separate
class ConvertWithGUI.java to set up the model,
view, and controller classes from within a main
method by calling the GUIWindow constructor. We
call ConvertWithGUI.java the application class.
357.6 The Application
- ConvertWithGUI is the application class
367.6 Model/View/Controller Pattern
- GUIWindow is the main view class it
- instantiates and maintains a reference to the
data model class Thermometer - instantiates and maintains references to data
fields and the command button - adds widgets to windows container
- instantiates and attaches a FahrenheitListener
object to the command button. The
FahrenheitListener class is the controller class.
377.6 The View Class
Example 7.5 GUIWindow.java
387.6 The View Class
Example 7.5 GUIWindow.java (cont.)
397.6 The Controller Class
Example 7.5 GUIWindow.java (cont.)
407.6 JTextField Methods
Table 7-4 Some JTextField methods
If you have a JTextField variable named fahrFld
that you have declared and instantiated in a GUI
program, then when it loads you can make the
cursor go immediately to fahrFld without the user
clicking the mouse in the field by using the line
of code fahrFld.requestFocus()
417.6 JTextField ActionListeners
After entering data into a JTextField named
fahrFld , if you want the input to be processed
by pressing the enter or return key on your
keyboard without clicking a GUI button, you can
add an action listener to the JTextField
variable. fahrFld.addActionListener(new
FahrenheitListener()) If you have a private
inner class already defined named
FahrenheitListener that you are using for a
button, then you simply add an anonymous call to
the class as the parameter for the
addActionListener ( ) method as seen above.
427.6 GUI programs are event-driven
- GUI programs are event-driven.
- when a program opens, it waits for events
- Events are generated when the user interacts with
the GUI by entering data in text fields, clicking
buttons, and making selections from menus or
other GUI components. - Events invoke controller classes, which in turn
invoke model classes.
437.6 GUI Layouts
- The 3 most commonly used simple layouts are
- BorderLayout
- FlowLayout
- GridLayout
- BorderLayout is the default layout for JFrame and
JApplet programs. So there is no need to set the
layout of the GUI. - To set the layout to a different one
- Container c getContentPane()
- c.setLayout(new FlowLayout( ) ) or
- c.setLayout(new GridLayout( ) )
447.6 GUI Layouts
- Because the program may use an overall layout for
the container and then contain JPanel objects in
each region of a layout, sometimes we place
individual layouts inside the panels to further
control things. - Here is an example
- JPanel dataPanel new JPanel(new GridLayout(2,
2) - . // add the components to this panel
- JPanel buttonPanel new JPanel(new GridLayout(1,
4) - . // add the components to this panel
- Container c getContentPane()
- c.add(dataPanel, BorderLayout.CENTER)
- c.add(buttonPanel, BorderLayout.SOUTH)
457.6 Alternate GridLayout Constructor
- Instead of
- JPanel dataPanel new JPanel(new GridLayout(2,
2)) - You can use
- JPanel dataPanel new JPanel(new GridLayout(2,
2, 5, 3)) - This constructor call takes 4 parameters. The
first two are still the number or rows and
columns and the third is the horizontal gap
between columns and the fourth parameter is the
vertical gap between rows. For more info on
GridLayout - http//java.sun.com/j2se/1.5.0/docs/api/java/awt/G
ridLayout.html
467.6 Making Temperature Conversion Go Both Ways
Figure 7-5 Temperature converter that goes both
ways
477.6 Making Temperature Conversion Go Both Ways
- Alterations
- Declares and instantiates second button
- Adds button to button panel
- Creates listener object and attaches it to button
- Defines a separate listener class that converts
from Celsius to Fahrenheit
487.6 Making Temperature Conversion Go Both Ways
Example 7.6 Listener to convert Celsius to
Fahrenheit
497.6 Making the Temperature Conversion Robust
Example 7.7 Robust listener for number format
errors
507.6 Making the Temperature Conversion Robust
Figure 7-6 Responding to a number format error
51JTextAreas (not in Chapter 7)
- JTextAreas are similar to JTextFields. You can
construct a text area with 10 rows and 20 columns
to display textual information as follows - private JTextArea output new JTextArea(10, 20)
52JScrollPanes (not in Chapter 7)
- You can force a JTextArea to display scroll bars
by wrapping it in a JScrollPane as follows - private JTextArea output new JTextArea(10, 20)
- JScrollPane myJScrollPane new
JScrollPane(output) - Now a user can scroll down a text area and view
information that is being displayed beyond the
bottom of the window. - The user of the program can then scroll down or
up at will to view any of the information in the
window.
53Setting Wheel Scrolling
- You can also make JTextAreas respond to the
scroll wheel on a mouse by using the following
code - private JTextArea output new JTextArea(10, 20)
- Code in the init() method
- JPanel textPanel new JPanel()
- JScrollPane myJScrollPane new
JScrollPane(output) - myJScrollPane.setWheelScrollingEnabled(true)
- textPanel.add(myJScrollPane)
54Summary
- The terminal input/output (I/O) interface can be
extended to handle repeated sets of inputs. - Query-based pattern
- Menu-driven pattern
- The graphical user interface (GUI) allows user to
interact with a program by displaying window
objects and handling mouse events.
55Summary
- Terminal-based program Program controls most of
the interaction with the user - GUI-based program Driven by user events
- Two primary tasks of a GUI-based program
- Arrange window objects
- Handle user interactions