Download COIT11222__Week_03__Lecture

Document related concepts
no text concepts found
Transcript
COIT 11222 – Visual Programming
• Lecture:
Week 3
References:
• Java Programming - Complete
Concepts and Techniques,
3rd Edition, Shelly Cashman et al.
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 1
Topics For This Week
•
•
•
•
•
•
•
•
•
Review all Java Program Types covered so far.
Java Hints and Tips
Good Coding Tips
Class Design - Methods and Data
Naming Conventions
Storyboards
Applets
HTML – basics
Creating and Working with GUI Components (Labels,
TextFields, and Buttons).
• Applets - Improving the Look and User Friendliness
• Data Validation and Range Checking Inputs
• Assignment 1 = 50%
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 2
Review of all Java Program Types
covered so far
• This week we start by reviewing all of the
program types covered so far in this course:
– Console Apps – general form
– Console – BufferedReader
– Console – Scanner
– Console – Swing Dialogs
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 3
Review of all Java Program Types
covered so far (cont)
• In addition, some probing questions will be
asked, and these should hopefully help
improve your understanding of everything
covered so far.
• Please Note: if you have printed these slides
out (or are reading them electronically), then
the questions and answers will be visible – so
cover up the answers and try to work out the
answers for yourself before seeing the
answer – otherwise you will NOT learn !!!
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 4
Console Apps – General Form
// Imports
public class My_Class
{
public static void main (String[] args)
{
// Declarations
// Code
}
}
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 5
Console Apps – BufferedReader
//
//
//
Author:
Mike O'Malley
Source File: W02_11_BufferedReader.java
Description: Read in user input using BufferedReader.
import
import
import
import
java.util.Date;
java.io.BufferedReader;
java.io.InputStreamReader;
java.io.IOException;
public class W02_11_BufferedReader
{
public static void main (String[] args) throws IOException
{
Date
currDate
= new Date();
int
hours
= 0;
int
rate
= 0;
String
empName = "";
String
hoursStr = "";
String
rateStr
= "";
double
grossPay = 0.0;
System.out.println ("Wages Calculator - Today is " + currDate);
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 6
Console Apps – BufferedReader
(cont)
BufferedReader keyboardIn = new BufferedReader (
new InputStreamReader (System.in));
System.out.println ();
System.out.print ("Enter Employee Name : ");
empName
= keyboardIn.readLine ();
System.out.println ();
System.out.print ("Enter Hours Worked : ");
hoursStr = keyboardIn.readLine ();
hours
= Integer.parseInt (hoursStr);
System.out.println ();
System.out.print ("Enter Hourly Rate : ");
rateStr = keyboardIn.readLine ();
rate
= Integer.parseInt (rateStr);
grossPay = hours *
System.out.println
System.out.println
System.out.println
rate;
();
("Gross Pay = " + grossPay);
();
}
}
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 7
Console Apps – BufferedReader
(cont)
• In the prior BufferedReader example:
– Why do we add throws IOException to main ?
– Answer: As the programmer, we need to cater for I/O
Errors whenever we use BufferedReader.
– Why do we use Integer.parseInt(Str) statements ?
– Answer: With BufferedReader everything is read in as
strings, which we need to convert to numbers as
appropriate.
– Why don’t we need to import anything to use
System.out.println () ?
– Answer: The System class is automatically included in
every Java program.
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 8
Java Hints and Tips
• Shortcut #1: We can combine
commands in Java.
• For example, instead of this:
System.out.print ("Enter Hourly Rate : ");
Rate_Str = Keyboard_In.readLine ();
Rate
= Integer.parseInt (Rate_Str);
• we could do this (and do without
Rate_Str):
System.out.print ("Enter Hourly Rate : ");
Rate = Integer.parseInt (Keyboard_In.readLine());
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 9
Console Apps – Scanner
//
//
//
Author:
Mike O'Malley
Source File: W02_12_Scanner.java
Description: Read in user input using Scanner.
import java.util.Date;
import java.util.Scanner;
public class W02_12_Scanner
{
public static void main (String[] args)
{
Date
currDate = new Date();
int
hours
= 0;
int
rate
= 0;
String empName = "";
String hoursStr = "";
String rateStr = "";
double grossPay = 0.0;
System.out.println ("Wages Calculator - Today is " +
currDate);
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 10
Console Apps – Scanner (cont)
Scanner keyboardIn = new Scanner (System.in);
System.out.println ();
System.out.print ("Enter Employee Name
empName
= keyboardIn.nextLine ();
: ");
System.out.println ();
System.out.print ("Enter Hours Worked : ");
hours
= keyboardIn.nextInt ();
System.out.println ();
System.out.print ("Enter Hourly Rate
rate
= keyboardIn.nextInt ();
: ");
grossPay = hours * rate;
System.out.println ();
System.out.println ("Gross Pay = " + grossPay);
System.out.println ();
}
}
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 11
Console Apps – Scanner (cont)
• In the prior Scanner class example:
– Why don’t we add throws IOException to main ?
– Answer: The Scanner class handles I/O Errors for us
automatically – no need for us to handle them.
– Could we use Integer.parseInt(Str) statements ?
– Answer: Yes, we could read everything in as strings with
the nextLine () method and convert to integer (where
required) with Integer.parseInt(Str), but there is no need
to do this. The Scanner class provides nextInt,
nextDouble, etc methods – so we can simply use these
instead.
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 12
Console Apps – Swing
//
//
//
Author:
Mike O'Malley
Source File: W02_12_Scanner.java
Description: Read in user input and display output using Swing
Dialogs.
import javax.swing.JOptionPane;
// For Swing Dialogs
public class W02_13_Swing_Dialogs
{
public static void main (String[] args)
{
int
hours, rate;
String empID, hoursStr, rateStr;
double grossPay;
// Get User Input
empID
= JOptionPane.showInputDialog ("Enter Employee ID: ");
hoursStr = JOptionPane.showInputDialog ("Enter Hours Worked: ");
rateStr = JOptionPane.showInputDialog ("Enter Hourly Rate: ");
// Convert to Integers
hours
= Integer.parseInt(hoursStr);
rate
= Integer.parseInt(rateStr);
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 13
Console Apps – Swing (cont)
// Calculations
grossPay = hours * rate;
// Display Results
JOptionPane.showMessageDialog (null,
"Gross Pay = " + grossPay,
"Gross Pay", JOptionPane.INFORMATION_MESSAGE);
// Exit
System.exit(0);
// Program is ending normally.
}
}
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 14
Console Apps – Swing (cont)
• In the prior Swing App example:
– Why do we import javax.swing.JOptionPane ?
– Answer: We need to import this package to use
Swing dialogs.
– Why do we use Integer.parseInt(Str) ?
– Answer: With Swing dialog input, everything is read in as
strings, which we need to convert to numbers as
appropriate.
– Do we need the System.exit(0) ?
– Answer: Technically yes – applications that use a GUI
should be terminated with an exit (). (See Wee 2’s lecture
material).
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 15
Console Apps - Summary
• We have now reviewed all program types
covered so far in this course:
– Console Apps – general form
– Console – BufferedReader
– Console – Scanner
– Console – Swing Dialogs
• Any questions on anything so far ?
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 16
Class Design - Methods and Data
• Regardless of the application type, such as
Console Application, Applet, etc, we can (and
soon will be) creating classes with multiple
methods.
• We can declare data at the class level, which
any method in our class can access.
• In addition, each method can declare its own
data, which only it can access.
• That is, data declared inside the method is
said to be local to the method.
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 17
Class Design - Methods and Data
(cont)
• General example:
public class myClass
{
// Class data
public method1
{
// method 1's data.
}
public method2
{
// method 2's data.
}
public method3
{
// method 3's data.
}
}
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 18
Class Design - Methods and Data
(cont)
• In the example on the prior slide:
– method1 can access all class data and any local
data declared in method1.
– Also method2 can access all class data and any
local data declared in method2.
– However, no method can access data declared in
another method. e.g. method1 cannot access
method2's data.
• This is illustrated further on the next slide.
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 19
Class Design - Methods and Data
(cont)
• Bank Account example (with 2 methods):
public class bankAccount
{
String acctName;
double acctBalance;
public void acctDeposit
{
double depositAmount = 0.0;
// Code to get valid amount, and adjust account balance.
}
public void openAccount
{
String confirmAccountCreation;
// Code to prompt user for valid name and balance.
}
}
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 20
Class Design - Methods and Data
(cont)
• In the example on the prior slide:
– The class data is acctName and acctBalance.
– The acctDeposit method can access all class
data and all local data it declares.
– Also, the openAccount method can access all
class data and all local data it declares.
– However, openAccount cannot access data that
is local to acctDeposit, such as depositAmount.
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 21
Class Design - Methods and Data
(cont)
• So, what data should be declared as class
data and what should be declared local to a
method ?
• If the data legitimately relates to the purpose
of the class, then it probably should be class
data.
• If the data is used by a method to do its job
and is not appropriate for use or re-use by
other methods, then it should be declared
local to the method.
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 22
Class Design - Methods and Data
(cont)
• Examples of class data:
– Bank Account class – account name, account ID,
account balance, account address, credit rating,
etc are all valid class data items.
– Student class – student id, student name, phone,
email, address, grades, results, etc are all valid
class data items.
– Product class – product id, product name, price,
quantity in stock, etc are all valid class data
items.
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 23
Class Design - Methods and Data
(cont)
• Examples of method data (data that should
be declared local to a method):
– end-of-file / end-of input flags
– counters
– data valid flags
– temporary variables, such as variables used to
hold input while it is being processed / validated.
• Keep these strategies in mind from now on.
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 24
Naming Conventions – Sun / Java
• Sun (and the vast majority, if not all, Java text books)
recommend the following Java naming conventions:
– Class names in Title Case (lower case with the first letter of each
word capitalized). For example:
public class ShoppingCart () …
– Methods and data item names in lower case with the first letter of
each internal word (after the first word) capitalized. For example:
addItemToShoppingCart ();
ShoppingCart
myShoppingCart;
– Constants should be declared with a final keyword (so that no
method can change their value), and should be named in uppercase
words separated by underscores. For example:
final int MIN_LENGTH = 4;
final int MAX_LENGTH = 999;
• Reference:
http://java.sun.com/docs/codeconv/html/CodeConventions.doc8.html#367
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 25
Naming Conventions (cont)
• The *VAST* majority of Java text books and
programmers use these naming conventions.
• The majority of recent C++ text books have
also adopted similar naming standards.
• However, these naming standards are
different to those commonly used for other
programming languages, such as SQL,
Visual Basic, COBOL, Delphi, Pascal, etc.
• As such, you may adopt an alternate naming
convention – see next slide.
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 26
Naming Conventions - Alternate
• The following is a very common naming convention
that is used widely in (non-Java) industry:
– Classes, Methods, and data item names in title case with
the words separated by underscores. For example:
public class Shopping_Cart () …
Add_Item_To_Shopping_Cart ();
Shopping_Cart
My_Shopping_Cart;
– Constants – same convention as prior slide - declared
with a final keyword (so that no method can change their
value), and should be named in uppercase words
separated by underscores. For example:
final int MIN_LENGTH = 4;
final int MAX_LENGTH = 999;
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 27
Naming Conventions (cont)
• When you are working for a client / employer, then
you will have to adopt whatever naming and other
standards that they use.
• However for your work at CQU, you can use
whatever naming convention that you like – as long
as you are consistent within your own work.
• NOTE: The aim is to always make your code as
easy to understand and maintain as possible. So,
using meaningful names, commenting your code,
using a good design, etc are far more important
than the naming convention you use.
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 28
Applets
• Client-side programs executed as part of a
displayed Web page. Example:
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 29
Applet - General Form
• Unlike Console Applications, Applets do NOT
have a main method.
• Basic Applets have the following methods:
– init() - adds GUI components to the user
interface, setup / adds listeners for button or item
clicks, loads logo(s).
– paint() - draws logo(s) on screen.
– Click Handlers – either or both of these:
• An ActionListener (actionPerformed) method to act on
button clicks.
• An ItemListener (itemStateChanged) method to act on
item clicks, such as checkboxes, choices, etc.
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 30
Applet - General Form (cont)
// Imports
public class My_Applet extends Applet implements ActionListener, ItemListener
{
// Declare Class Data.
// Declare and Construct GUI Components.
public void init()
{
// Adds GUI components, setup / adds listeners for button
// or item clicks, loads logo(s).
}
public void actionPerformed (ActionEvent e)
{
// Act on button clicks. e.g. when user clicks "Calculate" button.
}
public void itemStateChanged (ItemEvent choice)
{
// Act on item clicks. e.g. when user clicks a checkbox.
}
public void paint (Graphics g)
{
// Draws logo(s) on screen.
}
}
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 31
Applet - imports
• For Applets, just as with any Java application type,
you can import all of the required packages using
"*", for example:
import java.applet.*;
// For Applet support
import java.awt.*;
// For GUI components
import java.awt.event.*; // For event handling
• Or, you can just specify the items you specifically
need in your Applet, for example:
import
import
import
import
import
import
// etc
java.applet.Applet;
java.awt.Label;
java.awt.TextField;
java.awt.Button;
java.awt.event.ActionListener;
java.awt.event.ActionEvent;
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 32
Applet – Wages Calculator Example
• Let's begin by looking at the code for an
entire Applet – which is an Applet version of
the Wages Calculator console applications
we developed last week (and reviewed earlier
this week).
• Our Wages Calculator Applet will have a
basic Graphical User Interface (GUI) with:
– 3 TextFields (data entry boxes),
– 5 Labels (for displaying messages and
information to the user)
– 1 Button, for calculating pay details.
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 33
Storyboards
• Storyboards are quick sketches / drawings of
what we want our application to look like.
• For this application, the design is very simple
– just a single screen with a few GUI
components, so drawing the Storyboard is
very easy.
• For more complex systems, there could be a
dozen (or more) Storyboards.
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 34
Applet – Wages Calculator Example
(cont)
• Here is a Storyboard of what we are aiming
for:
Gross Pay Calculator
Enter Employee ID:
Enter Hours Worked:
Enter Hourly Rate:
Calculate
Please enter values and click the 'Calculate' button !!
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 35
Applet – Wages Calculator Example
(cont)
• OK, let's begin with the class statement.
• We are developing an Applet, so we need to add
extends Applet to our public class … statement.
• In addition, we have a button which we need to
react to mouse clicks, so we need to add
implements ActionListener to our public class …
statement.
• It is a good idea to identify the application type in
the name as well. In this case, add "Applet" to the
class name.
• This will do nicely:
public class W03_02_Wages_Calc__Applet
extends Applet implements ActionListener
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 36
Applet – Wages Calculator Example
(cont) – class and GUI data
• Next, we need our class data:
String
int
double
Emp_ID;
Hours, Rate;
Gross_Pay;
• Then, we need to declare the GUI components we
need (5 Labels, 3 TextFields, and a button).
• Labels are used for displaying messages and
information to the user.
• To declare a label, we do the following:
Label My_Label = new Label ("label text");
• This code declares a label, called My_Label and
assigns it the text "label text".
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 37
Applet – Wages Calculator Example
(cont) – class and GUI data
• TextFields are data entry boxes.
• To declare a TextField, we do the following:
TextField My_TextField = new TextField (20);
• and this declares a TextField, called My_TextField
and makes it 20 characters wide.
• The user will be able to type 100's of characters into
this TextField, but only 20 characters
(approximately) will be visible at any time.
• If the TextField contains more than 20 characters,
then the user can use the left and right arrow keys
to scroll through the text.
• A width of 20 is "overkill" for entering hours and pay
rates, so we could use 10 or something else if we
wanted.
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 38
Applet – Wages Calculator Example
(cont) – class and GUI data
• Buttons are labelled and shaded areas that
the user can click with the mouse that
perform a specific job. e.g. Calculate.
• To declare a Button, we do the following:
Button Calc_Button
= new Button ("Calculate");
• and this declares a button, called
Calc_Button and labels it "Calculate".
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 39
Applet – Wages Calculator Example
(cont) – class and GUI data
• OK, putting this all together, here is the code to
construct all our GUI components:
Label Window_Title_Label
= new Label
("Gross Pay Calculator");
Label Emp_ID_Label
= new Label
("Enter Employee ID:");
Label Hours_Label
= new Label
("Enter Hours Worked:");
Label Rate_Label
= new Label
("Enter Hourly Rate:");
Label Output_Label
= new Label
("Please enter values and click the 'Calculate' button !!");
TextField Emp_ID_TextField = new TextField (20);
TextField Hours_TextField = new TextField (20);
TextField Rate_TextField
= new TextField (20);
Button Calc_Button
= new Button ("Calculate");
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 40
Applet – Wages Calculator Example
(cont) – init () method
• The init () method is executed when the Applet is
loaded into the web browser and it can do a wide
range of things, including:
–
–
–
–
–
adding GUI components to the interface,
setup / add listeners for button or item clicks,
load logo(s) from file,
set the colour(s),
and so on.
• For this Applet, we only need the button to react to
mouse clicks, so we only have a ActionListener.
• We can add a GUI component to the user interface
with the following command:
add (GUI_Component_Name);
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 41
Applet – Wages Calculator Example
(cont) – init () method
• To make a button react to mouse clicks, we
need to assign an ActionListener to the
button.
• We can assign an ActionListener to a button
with the following command:
My_Button.addActionListener (this);
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 42
Applet – Wages Calculator Example
(cont) – actionPerformed () method
• OK, we are almost finished a very basic version of
our Applet.
• All we need to do now is get all user inputs,
calculate the pay, and display the output (via a
label).
• As with BufferedReader and SWING Input Dialogs,
all input into TextFields is a String.
• If we require the input in an integer, double, etc
format, then we can do the conversion using
parseInt, parseDouble, etc, just as we did with
String input in the BufferedReader and SWING
Input Dialogs examples covered earlier (and last
week).
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 43
TextField and Label – get, set, erase
• To get the contents of a TextField or Label, we use
the getText() method, for example:
Emp_ID = Emp_ID_TextField.getText();
String OL_Str = Output_Label.getText();
• To set a TextField or Label to a particular value, we
use the setText() method, for example:
Emp_ID_TextField.setText("ABC123");
Output_Label.setText("Greetings !!");
• To erase a TextField or Label, we can again use the
setText() method, for example:
Emp_ID_TextField.setText("");
Output_Label.setText("");
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 44
Applet – Wages Calculator Example
(cont) – actionPerformed () method
• For our Wages Calculator, we need to
convert the input data in the appropriate
TextFields into integers, as we can do this
using getText() and parseInt, as follows:
Hours = Integer.parseInt(Hours_TextField.getText());
Rate = Integer.parseInt(Rate_TextField.getText());
• We can then calculate the Gross Pay:
Gross_Pay = Hours * Rate;
• And display the output in a Label:
Output_Label.setText ("Gross Pay for '" +
Emp_ID + "' is $" + Gross_Pay);
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 45
Applet – Wages Calculator Example
(cont)
• Here is the complete Applet:
//
//
//
Author:
Mike O'Malley
Source File: W03_02_Wages_Calc__Applet.java
Description: Wages Calculator (very basic).
import
import
import
import
import
import
import
import
import
java.applet.Applet;
java.awt.Label;
java.awt.TextField;
java.awt.Button;
java.awt.Image;
java.awt.Graphics;
java.awt.Color;
java.awt.event.ActionListener;
java.awt.event.ActionEvent;
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 46
Applet – Wages Calculator Example
(cont)
public class W03_02_Wages_Calc__Applet extends Applet implements
ActionListener
{
// Declare variables
String Emp_ID;
int
Hours, Rate;
double Gross_Pay;
// Construct GUI Components
Label Window_Title_Label
= new Label
("Gross Pay Calculator");
Label Emp_ID_Label
= new Label
("Enter Employee ID:");
Label Hours_Label
= new Label
("Enter Hours Worked:");
Label Rate_Label
= new Label
("Enter Hourly Rate:");
Label Output_Label
= new Label
("Please enter values and click the 'Calculate' button !!");
TextField Emp_ID_TextField = new TextField (20);
TextField Hours_TextField = new TextField (20);
TextField Rate_TextField
= new TextField (20);
Button Calc_Button
= new Button ("Calculate");
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 47
Applet – Wages Calculator Example
(cont)
public void init()
{
// Set the foreground colour, add GUI components
// to the user interface, and activate a
// button (add a listener).
setForeground (Color.blue);
add (Window_Title_Label);
add (Emp_ID_Label);
add (Emp_ID_TextField);
add (Hours_Label);
add (Hours_TextField);
add (Rate_Label);
add (Rate_TextField);
add (Calc_Button);
add (Output_Label);
Calc_Button.addActionListener (this);
}
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 48
Applet – Wages Calculator Example
(cont)
public void actionPerformed (ActionEvent e)
{
// Get Text Input and Convert to Integers if required.
Emp_ID = Emp_ID_TextField.getText();
Hours = Integer.parseInt(Hours_TextField.getText());
Rate
= Integer.parseInt(Rate_TextField.getText());
// Calculate the Gross Pay.
Gross_Pay = Hours * Rate;
// Output the Gross Pay.
Output_Label.setText ("Gross Pay for '" +
Emp_ID + "' is $" + Gross_Pay);
}
}
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 49
HTML
• Because an Applet is intended to run in a WEB
Browser, we need to create a small (and very
simple) HTML file for each Applet we create.
• Recommended conventions / CAUTION:
– If your Java source file is called My_Applet.java, then call
the HTML file My_Applet.html
– If you rename your Applet, then don't forget to rename the
HTML file and update the applet code tag inside the
HTML file.
– Keep the HTML file in the same directory as the Java
source code.
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 50
HTML (cont)
• If you don't know HTML, don't panic !
• You only need two HTML tags:
– <HTML> … </HTML> which marks the start and end of
the HTML in the file.
– <applet …> … </applet> which specifies the applet that is
being loaded and the height and width of the window in
which it is displayed.
– Note: the applet tag must name the compiled Java code
(the .class file) NOT the Java source code (the .java file).
• Example:
<html>
<applet code = "W03_02_Wages_Calc__Applet.class"
width=500 height=500>
</applet>
</html>
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 51
Compiling Our Applet
• Assuming:
– You have created the HTML file, and placed it in
the same directory as your Java source code.
– Your source code has compiled 100% error free.
• We are now ready to compile and run our
Applet.
• To compile our Applet do either of the
following in TextPad:
– Select the Tools  Compile Java menu option.
– Or, simply hold down the Ctrl and 1 keys
simultaneously and release them.
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 52
Running Our Applet
• Note Well: You do NOT run a Java Applet
using the same commands that we used for
Console Applications.
• To run our Applet do either of the following:
– Select the Tools  Run Java Applet menu option.
– Or, simply hold down the Ctrl and 3 keys
simultaneously and release them.
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 53
Running Our Applet (cont)
• When you do this, a dialog will be displayed
with a drop down list of HTML files in the
current directory.
• The HTML file required to load your Applet
may NOT be the default HTML file selected.
• WARNING: Make sure you carefully check to
make sure the correct HTML file is selected
before clicking the "Yes" button – otherwise
you will run the wrong Applet.
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 54
Running Our Applet (cont)
• Here we have selected the correct HTML file
from the drop down list and we can now click
the "Yes" button:
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 55
Running Our Applet (cont)
• If you have followed the above carefully, then
your Applet should now appear in the
AppletViewer supplied with Java:
UGLY !!
 UGLY !!
 UGLY !!
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 56
Applets - Improving the Look
• As you can see, our Applet is pretty ugly !!!
• For example:
– The Employee ID Label and TextField are up with
the application title. We want these to drop down
a line.
– The Hourly Rate Label is on one line (with the
hours worked Label and TextField), but the
Hourly Rate TextField is on the next line.
– We want the Calculate button to drop down onto
its own line.
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 57
Applets - Improving the Look (cont)
• The problem is that we don't have ANY
control over where GUI components are
placed on the screen.
• All we can do is add the components to the
screen, so we can control the order in which
they are added, but we cannot specify where
they are positioned.
• Later in this course, we cover Layout
Managers which enable us to use some
advanced techniques to control the look of
our application.
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 58
Applets - Improving the Look (cont)
• To improve the look of our Applet, at this early
stage in the course, we only have 2 weapons
in our arsenal:
– Adjust the height and width of our Applet's
window (via the height and width values in our
HTML file). This can force GUI components to
drop down onto the next line.
– We can space pad labels (or add additional
labels which are set to one or more spaces) to try
and force GUI components to drop down onto the
next line.
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 59
Applets - Improving the Look (cont)
• The key is to experiment.
• Make a change to the source code (and/or HTML
file), re-compile and re-run the Applet, and see what
the effect is.
• Concentrate on the topmost GUI components first –
get these looking good first, and then worry about
the components below these.
• Keep tweaking and trying until the Applet looks OK.
• Do NOT spend hours on this.
• As mentioned earlier, we will be covering Layout
Managers later which make it much easier to
control the look of your application.
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 60
Applets - Improving the Look (cont)
• For our Wages Calculator Applet, the following changes were required.
• Space padding labels:
Label Window_Title_Label
= new Label
("
" + "Gross Pay Calculator" +
"
");
Label Emp_ID_Label
= new Label
("
" + "Enter Employee ID:");
Label Hours_Label
= new Label
("
" + "Enter Hours Worked:");
Label Rate_Label
= new Label
("
" + "Enter Hourly Rate:");
• Tweak the height and width values in its HTML file:
<html>
<applet code =
"W03_02_Wages_Calc__Applet__Nice_Layout.class"
width=370 height=175>
</applet>
</html>
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 61
Applets - Improving the Look (cont)
• Before (ugly !!):
COIT 11222 - Visual Programming
After (nice !!):
Author(s): Mike O’Malley
Slide: 62
Data Validation
• In Week 2, we introduced exceptions. Here
is a quick recap …
• If invalid data is encountered, then various
methods will raise exceptions, such as:
int avgAge = Integer.parseInt("1234xyz");
• Unhandled exceptions will cause your
program to crash. For now, we will have to
live with this.
• In a future lecture, we will cover exception
handling.
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 63
Data Validation (cont)
• So, for now, we need to assume that the user
will enter reasonable data. e.g. an integer is
entered when an integer is required, etc.
• When we cover exception handling in a future
lecture, then we will be able to really validate
inputs.
• However, even though our programs will
currently crash if the user enters text in a field
that should contain an integer, we can at least
range check the inputs and display an error
message if they are not valid.
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 64
Data Validation – Range Checking
• For example, if hours worked had to be between 10
and 60, then we could test this as follows:
if ((Hours < 10) || (Hours > 60))
{
// Inform the user of the error.
}
• So, what is the best way to inform the user ?
• Whatever we do, the error message *must* be
meaningful and informative.
• Something like "Invalid input – please try again" is
NOT acceptable – it doesn't tell the user what is
wrong or why.
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 65
Data Validation – Range Checking
(cont)
• To inform the user of an error, we could
setText a Label. However, they may not
notice the label change (especially on a
crowded screen) and they may wonder why
the application seems not to be responding.
• A better and more obvious way is to display a
SWING Output dialog. (Yes, we can still use
all types of SWING Dialogs with Applets),
• Or, we could do both – so that the user can
still see what the problem is after they click
the OK button on the dialog.
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 66
Data Validation – Range Checking
(cont)
• So, let's do this.
if ((Hours < 10) || (Hours > 60))
{
// Inform the user of the error.
Output_Label.setText
("Error: Hours must be between 10 and 60 !");
JOptionPane.showMessageDialog (null,
"Hours Error !",
"Error: Please enter an Hours Worked value " +
"between 10 and 60 !",
JOptionPane.ERROR_MESSAGE);
}
• Exercise: There are two issues with this code ! Can
you identify these ?
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 67
Data Validation – Range Checking
(cont)
• Answer: Issues with the code (on the prior slide):
– Issue #1: If hours is outside the desired range, then an
error message is displayed, but the program continues on
to check the other inputs and do the calculations and
display the results. We want the program STOP if an
error is encountered. How do we do this ?
– Answer: Use if … else if … else … to only continue
processing if all is OK.
– Issue #2: The values 10 and 60 are repeated
everywhere. If these change, we need to change our
code in multiple places – a potential maintenance
nightmare. How do we fix this ?
– Answer: 10 and 60 are important threshold values that
should be made constants. These constants should then
be used in all range checks, error messages, etc.
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 68
Data Validation – Range Checking
(cont)
• Let's now fix these issues !!
• In addition, we will also range check the hourly rate, which
must be between 12 and 25.
• And, we will only proceed with subsequent validations and
processing if no errors have been encountered so far.
• First, we need some constants. We will declare these at
class level (to make them available to all methods):
// Global
final int
final int
final int
final int
Constants
HOURS_WORKED_MIN
HOURS_WORKED_MAX
HOURLY_RATE_MIN
HOURLY_RATE_MAX
=
=
=
=
10;
60;
12;
25;
• Now we can use these and fix the issues identified.
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 69
Data Validation – Range Checking
(cont)
public void actionPerformed (ActionEvent e)
{
// Get Text Input and Convert to Integers if required.
Emp_ID
= Emp_ID_TextField.getText();
Hours
= Integer.parseInt(Hours_TextField.getText());
// Let's range check the Hours Worked ...
if ((Hours < HOURS_WORKED_MIN) || (Hours > HOURS_WORKED_MAX))
{
// Invalid Hours Worked - inform the user of the error.
Output_Label.setText
("Error: Hours Worked must be between " +
HOURS_WORKED_MIN + " and " + HOURS_WORKED_MAX + " !");
JOptionPane.showMessageDialog (null,
"Error: Please enter an Hours Worked value between " +
HOURS_WORKED_MIN + " and " + HOURS_WORKED_MAX + " !",
"Hours Worked Error !", JOptionPane.ERROR_MESSAGE);
}
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 70
Data Validation – Range Checking
(cont)
else
{
// OK, Hours Worked is valid ...
// Now, let's range check the Hourly Rate.
Rate
= Integer.parseInt(Rate_TextField.getText());
if ((Rate < HOURLY_RATE_MIN) || (Hours > HOURLY_RATE_MAX))
{
// Invalid Hourly Rate - inform the user of the error.
Output_Label.setText
("Error: Hourly Rate must be between " +
HOURLY_RATE_MIN + " and " + HOURLY_RATE_MAX + " !");
JOptionPane.showMessageDialog (null,
"Error: Please enter an Hourly Rate between " +
HOURLY_RATE_MIN + " and " + HOURLY_RATE_MAX + " !",
"Hourly Rate Error !", JOptionPane.ERROR_MESSAGE);
}
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 71
Data Validation – Range Checking
(cont) and Good Coding Tips
else
{
// All input data is within the required ranges !!
// Calculate the Gross Pay.
Gross_Pay = Hours * Rate;
// Output the Gross Pay.
Output_Label.setText ("Gross Pay for '" +
Emp_ID + "' is $" + Gross_Pay);
} // End of if ((Rate < HOURLY_RATE_MIN) ...
} // End of if ((Hours < HOURS_WORKED_MIN) ...
} // End of Method actionPerformed
• Good Coding Tip #1: For long if tests, nested if tests,
methods, and blocks of code, it is a good idea to put
comments after the closing brace } so you can easily tell
what the block of code is and what the brace belongs to.
(See above).
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 72
Good Coding Tips
• Good Coding Tip #2: Don't make the user guess
what the valid ranges are for inputs. Instead, add
some hints to the screen. e.g. in labels. We can
use our constants for this as well, for example:
Label Hours_Label = new Label ("
" +
"Enter Hours Worked (" + HOURS_WORKED_MIN + " - " +
HOURS_WORKED_MAX + "):");
Label Rate_Label = new Label ("
" +
"Enter Hourly Rate (" + HOURLY_RATE_MIN + " - " +
HOURLY_RATE_MAX + "):");
• Even this small change makes our application much
more User Friendly.
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 73
Good Coding Tips
• After updating our source code and recompiling and re-running, here is the result:
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 74
Assignment 1 = 50%
• You can now complete about 50% of Assignment 1.
• Before you start Assignment 1, make sure you:
– Thoroughly read, review, and explore all topics discussed
in the lecture material for all weeks so far.
– Do all of the tutorial questions for all weeks so far.
– Follow the Development Hints and Tips in the assignment
specification (Course Profile).
• Next week, we cover:
– User defined methods,
– Exception handling,
– Logos, checkboxes, radio buttons, etc
• and this will allow you to complete 100% of
Assignment 1.
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 75
Summary of Topics Covered
•
•
•
•
•
•
•
•
•
Review all Java Program Types covered so far.
Java Hints and Tips
Good Coding Tips
Class Design - Methods and Data
Naming Conventions
Storyboards
Applets
HTML – basics
Creating and Working with GUI Components (Labels,
TextFields, and Buttons).
• Applets - Improving the Look and User Friendliness
• Data Validation and Range Checking Inputs
• Assignment 1 = 50%
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 76
End of Lecture
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 77