Title: COIT 11222 - Visual ProgrammingAuthor(s): Mike O
1COIT 11222 Visual Programming
- Lecture Week 4
- References
- Java Programming - Complete
- Concepts and Techniques,
- 3rd Edition, Shelly Cashman et al.
2Topics For This Week
- More GUI Development logos, drawString,
colours, checkboxes, radio buttons, etc - Pseudo Code and Flowcharts
- UML and UML Class Diagrams
- Math class, random numbers, etc
- Exception handling
- User Defined Methods
- Public Vs Private
- Lots of topics this week (again).
- We've had to set a cracking pace to cover enough
to allow you to do Assignment 1. - Dont Panic next week the pace is easier (for a
while). - Assignment 1 90
3Applets Adding a Logo
- Adding a logo to our Applet's window is very
easy. - First, we need to declare an Image object with
our other GUI Components - Image Logo
- Next, in our init () method, we need to load the
logo with the getImage() method - Logo getImage (getDocumentBase(),
"cqulogo.gif") - The getDocumentBase() tells Java to look for our
logo "cqulogo.gif" in the directory where our
source code is located.
4Applets Adding a Logo (cont)
- Finally, we need a paint method to draw the logo.
- The paint method has a Graphics object passed to
it (called g below) - public void paint (Graphics g)
-
- g.drawImage (Logo, 120, 160, this)
-
- The drawImage () method draws the logo 120 pixels
from the left and 160 pixels from the top of the
window.
5The paint() Method
- Accepts a Graphics object as a parameter
- The Graphics object is commonly referred to by
the variable name g (we could call it anything we
wanted, but we will assume it is called g). - The variable g is automatically created and
initialized in the init() method - The variable g is a reference variable (a
specific instance of an object). - The return type is void (it returns nothing).
6Applets Adding a Logo (cont)
- If we put the logo "cqulogo.gif" in the same
directory as our Java source code, and re-compile
and re-run our Applet, we will see
7Applets Adding a Logo (cont)
- Some examples in some text books load the logo
from file and draw it in the paint method. - For example
- public void paint (Graphics g)
-
- Logo getImage (getDocumentBase(),
- "cqulogo.gif")
- g.drawImage (Logo, 120, 160, this)
-
- However, this isnt ideal because the logo is
re-loaded every time paint is executed.
8Paint and drawString
- The paint method can also use the drawString
method to draw text directly onto the user
interface. - For example
- g.drawString ("My Text", 100, 200)
- Draws My Text 100 pixels from the left and 200
pixels from the top of the window. - If it is drawn in the same place as any labels,
buttons, or other GUI components, then the drawn
text goes behind these GUI components. - If it is drawn in the same place as the logo,
then it will go on top of the logo or behind the
logo depending on the order in which they are
drawn.
9Paint and drawString (cont)
- Example
- public void paint (Graphics g)
-
- g.drawImage (Logo, 120, 200, this)
- g.drawString ("Hi there _at_ 220, 160", 220,
130) - g.drawString ("Hi there _at_ 220, 220", 220,
220) - g.drawString ("Hi there _at_ 220, 300", 220,
250) -
10Paint and drawString (cont)
- The first drawString outputs some of the text
behind the Calculate button. The next, on top of
the logo, and the third below the logo.
11Colour Background and Foreground
- The setForeground and setBackground enable you to
set the foreground and background colours. - Examples
- setForeground (Color.blue)
- setBackground (Color.green)
- The predefined colours are
- black blue cyan darkGray
- gray green lightGray magenta
- orange pink red white
- yellow
12Colour Background and Foreground (cont)
- Or, you can specify millions of other colours
using red, green, and blue (RGB) values between 0
and 255. - Example, set the colour directly
- setBackground (new Color(44,55,200))
- Or, define a colour and then use this
- Color Back_Col new Color(44,55,200)
- setBackground (Back_Col)
13Colour Background and Foreground (cont)
- For the Applets background, and for the
foreground or background of any text written to
the interface with drawString, the colours are
set / changed / updated whenever the Applets
background and foreground colours are changed.
Example - setForeground (Color.blue)
- setBackground (Color.green)
- This affects the Applets colours and the colours
of all text written to the interface with
drawString. - This does NOT affect any GUI components (labels,
buttons, etc) that have already been added to the
user interface.
14Colour Background and Foreground (cont)
- For GUI components (labels, buttons, etc) you can
either - Set the interface's colours before adding the
components to the interface (they will then be
added with the interface's colour), OR, - Set the component colours at any time by invoking
the setForeground and setBackground specifically
for each required GUI component - My_Label.setBackground (new Color(44,55,200))
- My_Label.setForeground (Color.blue)
15Checkboxes
- A checkbox is a graphical component that can be
in either an "on" (true) or "off" (false) state. - Clicking on a check box automatically changes its
state from "on" to "off" or from "off" to "on ". - To use Checkboxes, you need the following import
- import java.awt.Checkbox
- Checkboxes can be created much like other GUI
Components. Example (Customer Check-in System) - Checkbox Deluxe_Checkbox new Checkbox ("Deluxe
Room") - Checkboxes are added to the user interface in
exactly the same way as any other GUI Component
via the add command in the init method - add (Deluxe_Checkbox)
16Checkboxes (cont)
- To programmatically check a checkbox, use the
setState() method. Example - Deluxe_Checkbox.setState (true)
- And, to uncheck the checkbox
- Deluxe_Checkbox.setState (false)
- To determine if a checkbox is checked, use the
getState() method. Example - if (Deluxe_Checkbox.getState () true)
-
- // Customer wants a Deluxe Room.
17Radio buttons (Checkbox Group)
- Checkboxes in a group are called Radio Buttons,
and only one Radio Button in the group can be
checked (selected) at any time. - To create checkboxes in a group, you need to
import the required packages - import java.awt.Checkbox
- import java.awt.CheckboxGroup
- And then create a checkbox group. Example
- CheckboxGroup Credit_Cards new CheckboxGroup ()
COIT 11222 - Visual Programming Author(s) Mike
OMalley Slide 17
18Radio buttons (Checkbox Group) (cont)
- And then add checkboxes to this group. Example
- Checkbox Visa_Card
- new Checkbox ("Visa Card", true,
Credit_Cards) - Checkbox Master_Card
- new Checkbox ("Master Card", false,
Credit_Cards) - Checkbox AMEX_Card
- new Checkbox ("AMEX Card", false,
Credit_Cards) - The Visa card will be selected by default,
because it has true specified. - As before, the checkboxes are added to the user
interface via the add() method in the init()
method - add (Visa_Card)
- add (Master_Card)
- add (AMEX_Card)
19Radio buttons (Checkbox Group) (cont)
- Screen shot (Smoking / Non Smoking discussed on
following slides)
20Radio buttons (Checkbox Group) (cont)
- And, you use getState and setState methods (as
before with single checkboxes) to get and set the
state of these radio buttons. - Example of getting the state
- if (Visa_Card.getState () true)
-
- Paying_Str "Visa Card"
-
- Example of setting the state
- Master_Card.setState (true)
21Hidden Checkbox
- For some applications, a program needs to provide
a default selection for one of the radio buttons.
That is, one of the radio buttons will be
checked / selected by default. - However, for other situations, your program may
need to force the user to select one of the radio
buttons before continuing.Example a motel /
hotel Customer Check-in System may require the
customer to actively specify a smoking or
non-smoking room. Why ? - If a smoker is placed in a non-smoking room, and
they smoke, then this can cause a great deal of
cleanup, and expense for the hotel. - e.g. Many hotels in Brisbane now charge a cleanup
fee of 150 for smoking in a non-smoking room. - Similarly, if a non-smoker is checked into a
smoking room, then they may feel quite ill
because of the lingering smoke and residue from
years of smoking in the room.
22Hidden Checkbox (cont)
- If your program needs to force the user to select
a checkbox, then one way to achieve this is the
hidden checkbox method. - This involves creating an extra checkbox in the
group, but not adding it to the user interface. - This checkbox will be checked by default, and the
application will make sure that it is NOT checked
before proceeding with processing. - That is, it forces the user to check one of the
visible checkboxes.
23Hidden Checkbox (cont)
- First, we need to create the Checkbox group
(including the Hidden checkbox) - CheckboxGroup Smoking_Group new
CheckboxGroup () - Checkbox Smoking_Checkbox
- new Checkbox ("Smoking", false,
Smoking_Group) - Checkbox Non_Smoking_Checkbox
- new Checkbox ("Non-Smoking", false,
Smoking_Group) - Checkbox Hidden_Checkbox
- new Checkbox ("Hidden", true,
Smoking_Group) - Then, add all checkboxes in the group to the user
interface, except the Hidden Checkbox - add (Smoking_Checkbox)
- add (Non_Smoking_Checkbox)
- So, only these two checkboxes will be visible to
the user and checkable by the user.
24Hidden Checkbox (cont)
- Then, when we are processing the customer check
in, we need to check if the Hidden checkbox is
still selected / checked, and, if it is, display
an error and prevent the check in from
proceeding - if (Hidden_Checkbox.getState () true)
-
- JOptionPane.showMessageDialog (null,
- "Please select SMOKING or NON-SMOKING
!!", - "Smoking Status", JOptionPane.ERROR_MESSAG
E) -
- else
-
- // Customer check in can proceed
-
25Hidden Checkbox (cont)
- As you can see, this technique can be very useful
when your application wants to force the user to
make a selection, rather than just accept the
default selection.
26Activating Checkboxes
- In Week 3 we saw
- To make a button react to mouse clicks, we need
to assign an ActionListener to the button.
Example - My_Button.addActionListener (this)
- We can make checkboxes and radio buttons (groups
of checkboxes) react to mouse clicks by assigning
an ItemListener to them in the init () method - My_Checkbox.addItemListener (this)
- Note Add a listener to each Checkbox in the
group. You dont add the listener to the
CheckboxGroup object.
27Activating Checkboxes (cont)
- We also need to tell Java that we want the Applet
to be able to deal with active checkboxes. - To do this, we need to add "implements
ItemListener" to the class statement. - For example, if you need just ActionListener
- public class ... extends ...
- implements ActionListener
- But, if you need both ActionListener and
ItemListener - public class ... extends ...
- implements ActionListener, ItemListener
28Activating Checkboxes (cont)
- Finally, we need to implement an itemStateChanged
method - public void itemStateChanged (ItemEvent choice)
-
- // Enter code below that needs to run
- // when checkbox is clicked on by the user.
- // public void itemStateChanged
29Activating Checkboxes (cont)
- In most cases, where a checkbox is active, all
the itemStateChanged method will do is update
labels, perform simple calculations, and so on. - However, in some cases, the itemStateChanged
method may do a lot more, especially if your
application has no buttons on the user interface.
30Activating Checkboxes (cont)
- Example
- public void itemStateChanged (ItemEvent choice)
-
- // The user has clicked on a checkbox, let's
find out - // which one and update a label's text and
colour. - if (Smoking_Checkbox.getState () true)
-
- Output_Label.setText ("You are a smoker.")
- Output_Label.setForeground (Color.blue)
-
- else if (Non_Smoking_Checkbox.getState ()
true) -
- Output_Label.setText ("You are a
NON-smoker.") - Output_Label.setForeground (Color.red)
-
- // public void itemStateChanged
31Activating Checkboxes (cont)
- Ref W04_01_Customer_Check_In_System.java
32Swing Vs AWT
- All of the graphical user interface (GUI)
components we use in this course are AWT
Components. - AWT stands for Abstract Windows Toolkit,
- AWT provides a set of basic GUI components
(labels, buttons, textfields, menus, etc) that
are easy for beginner programmers to understand
and use. - In Java, there are Swing Dialogs, which we have
also been using a lot so far. - However, there are also Swing Components, which
you can use instead of the AWT Components that we
have been using so far. - We do not cover Swing Components in this course.
33Swing Vs AWT (cont )
- With SWING, you get improved versions of all of
the AWT components as well as a whole range of
new components. - Swing Components look a lot nicer than AWT
components, and also provide more functionality
and give the programmer a lot more control over
the look and feel of the application. - Swing Components allow you to develop very sexy
and very complex interfaces.
34Swing Vs AWT (cont )
- For example
- Swing buttons and labels can display images and
text. AWT buttons can only display text. - You can put borders around most Swing components.
- For our purposes, in this course, radio buttons
are multiple checkboxes in an AWT checkbox group. - However, Swing supports a proper Radio button
component. - With Swing its a case of more, more, more more
functionality, more control, better look and
feel, etc. - However, all of this comes at a price Swing
Components are more complex to use.
35Swing Vs AWT (cont )
- Java text books often introduce AWT first and
then move onto Swing because AWT is easier to
work with, the AWT components are simpler and
have fewer options, and there are less components
to deal with. - However, AWT isn't really that much simpler.
- In fact, introducing AWT first can lead to
confusion and frustration when you are going to
move to Swing later. - The problem is that (from a programming point of
view), changing an application over from AWT to
Swing is a bit of a pain - you need to change
components (Label -gt JLabel, etc), change the
code behind the scenes, and do quite a bit of
messing about.
36Swing Vs AWT (cont )
- Prior to 2008-T1, we covered Swing and AWT
components in this course. However, the decision
was made to only cover AWT from 2008-T1 onwards. - Note Well we do not cover Swing Components in
this course. - Swing Components are covered in the follow on
Java courses. - Please Note Radio Buttons Vs Checkbox Group.
In follow-on Java courses, if they say radio
buttons, then they mean proper Swing radio
buttons, not an AWT checkbox group !! - Please keep this in mind for the future !
37UML
- UML Unified Modelling Language
- UML is used specifically for OOD Object
Oriented Design - UML is a notation used to describe object
behaviours and interaction through a series of
documentation standards and diagrams such as
Class Diagrams, Event Diagrams, Use Cases, etc - Gaining wide popularity and use in industry.
38UML Class Diagram
- A UML Class Diagram shows for each class
- the class name
- class attributes, the data type for each
attribute, and whether it is public or private
and - class methods, the data type for each method, and
whether it is public or private. - Usually is used to indicate public, and for
private. - Note In this course, we are only dealing with
single class projects, so our UML Class
Diagrams will be very simple and only show a
single class.
39UML Class Diagram (cont ...)
- Example
- So, the Employee class has 5 data attributes (all
are private), and 3 public methods.
Employee ----------------------------------
---------------------- - Employee_ID int - Name
String - Address String - Date-of-Birth Date -
Salary float ------------------------------------
-------------------- calculateTax() float
calculateSuperAnnuation() float
deleteEmployee() bool
40Pseudo Code
- Pseudo Code, also called Structured English, is a
compact, informal, and high-level description of
a process or algorithm. - Pseudo Code allows the designer to focus on the
logic of the algorithm without being distracted
by details of a programming languages syntax. - Pseudo Code is great for specifying, documenting,
and clarifying user requirements, business rules,
and processing strategies and rules, and so on.
41Pseudo Code (cont)
- Pseudo Code should describe the entire logic of a
process or algorithm so that implementation
(programming) becomes the simple mechanical task
of translating the pseudo code line by line into
a programming language source code. - Recommendation Before jumping straight into
coding, ensure you explore and understand what is
required, and plan out what you are going to do
and how you are going to do it with pseudo code.
42Pseudo Code (cont)
- Example 1 Get Ready for Work
- Get out of bed
- Shower
- Brush teeth
- Comb hair
- Get Dressed
- etc
43Pseudo Code (cont)
- Example 2 Calculate Area of Rectangle
- Get height of rectangle
- Get width of rectangle
- Calculate area height width
- Example 3 Allocate an Airline Seat
- Before we could begin coding a Allocate an
Airline Seat function in Java (or any other
programming language) we would need to understand
exactly what is required to allocate an airline
seat.
44Pseudo Code (cont)
- For a first pass of the Allocate an Airline Seat
we might come up with the following - Get customers flight details and seat
preferences - Check each available seat on the flight against
the customers preferences. - Lock best seats (while customer chooses seat)
- Display list of best seats to customer.
- Get customers seat preference.
- Book airline seat for customer.
- However, we still could NOT turn this algorithm
into a real program. - Before we can do this, we will need to explore
and expand each of these steps.
45Pseudo Code (cont)
- For example, for Step 2 Check each available
seat on the flight against the customers
preferences, the pseudo code could be - Initialise Best Seats list
- For each seat on the flight
- If seat is available (not occupied / booked)
- If seat matches class preference (business,
economy, etc) ? - Add 10 to Seat Score
- If seat matches customers leg room preference ?
- Add 1 to Seat Score
- If seat matches customers window / aisle seat
preference ? - Add 2 to Seat Score
- And so on for other criteria e.g. Non /
Smoking ? Wing seat ? Proximity to Toilet ?
Front or rear of plane ? - If seat qualifies for Best Seats list, add it to
the list.
46Pseudo Code (cont)
- We have now expanded Step 2 slightly.
- But, we still are NOT at the stage where we can
turn this algorithm into a real program. - Before we can do this, we still need to explore
and expand various steps. - For example
- How do you add a seat to the Best Seats List ?
How are these seats stored ? Are they sorted ?
How ? When ? - How do you initialise the Best Seats List ?
- Where are seat details and seat allocations held
? How is this data accessed ? - Etc.
- Until everything is thoroughly explored and
documented, we cannot hope to develop a program
which performs the correct functionality.
47Pseudo Code (cont)
- There are many styles of Pseudo Code, such as
styles which are closer to programming languages,
like Java. - For example, we could also write the pseudo code
for step 2,as follows - Initialise Best Seats list
- While Still seats to check
- Load next seat
- If Seat.booked false
- If Seat.class Customer.class
- score score 10
- If Seat.leg room Customer.leg room
- score score 1
- If Seat.window / aisle Customer.window / aisle
- score score 2
- Etc for other criteria and steps ...
- End If
- End While
48Flow Charts
- Flowcharts are diagrams that can show exactly the
same information as pseudo code, but in
diagrammatic form. - Benefits over Pseudo Code
- Diagrams tend to be more attractive to look at
than pseudo code. - May appear more user friendly than pseudo code.
- People who are frightened by anything that looks
like a programming language may be more
comfortable with a diagram.
49Flow Charts (cont)
- Disadvantages compared to Pseudo Code
- It is usually more work to document something
with a flow chart than with pseudo code. - If requirements or processing rules change, then
it is usually much quicker and easier to update
pseudo code than flow charts. - An algorithm documented in a flow chart tends to
take up more space (more pages when printed out)
than the equivalent pseudo code. So, many pages
may be needed for a flow chart, when 1 page of
pseudo code may do the same job. - Flow charts tend to have a bad name amongst
programmers. - They went out of fashion in the 1970s - and many
claim that they still are ! ?
50Flow Charts (cont)
- The main symbols Examples
- (There are many others !!)
Process
Get Customers Leg Room Preference
Decision
Is Seat.Class Customer.Class ?
Process flow
Start / End Terminator
Data Store
Flight Seats
51Flow Charts (cont)
START
Is Seat.class Customer.class ?
Yes
Initialise Best Seats list
score score 10
No
No
Is Seat booked?
Yes
Is Seat.leg room Customer.leg room ?
Yes
score score 1
Still Seats to Check ?
Yes
Load next seat
No
Is Seat.window/aisle Customer.window/aisle ?
No
Yes
score score 2
Etc for other criteria and steps ... Need to
expand this
No
END
52Essential Skills
- All programmers (and all students in this course)
need to be able to convert between the following - Pseudo Code
- Flow Chart
- Java Program code
- This is an essential skill !!
- Ensure you get practice with doing this.
COIT 11222 - Visual Programming Author(s) Mike
OMalley Slide 52
53Math Class
54Math Class (cont)
- Example 1 To set a variable of type double to a
random number between 0 and 1 - double d1 Math.random ()
- Example 2 To set a variable of type double to a
random number between 0 and 80 - double d1 80 Math.random ()
55Math Class (cont)
- Exercise How could you set a variable of type
double to a random number between 10.0 and 90.0 ? - Solution below.
- Answer
- double d2 10.0 80.0 Math.random ()
56Math Class (cont)
- Exercise How could you set a variable of type
integer to a random integer between 10 and 90 ? - Solution below.
- Answer
- int i2 (int)(10.0 80.0 Math.random ())
57Exception Handling
- An exception is an event resulting from an
erroneous situation which disrupts normal program
flow. - Exception Handling is the technique of planning
for possible exceptions by directing the program
to deal with them gracefully, without
terminating, crashing, or producing ugly error
messages that the user of the program should not
be subjected to. - e.g. internal Java error messages.
58Exception Handling (cont)
- Three kinds of exceptions
- Input Output (I/O)
- Run-time
- Checked
- The compiler checks each method to ensure each
method has a handler to deal with the exceptions.
59Exception Handling (cont)
- There are 4 Java commands to deal with
exceptions - try
- throw
- catch
- finally
- The try statement identifies a block of
statements that may potentially throw an
exception.
60Exception Handling (cont)
- The throw statement transfers execution from the
method (or block of code) that caused the
exception to the exception handler. - The catch statement
- Contains the code to deal with the exception,
providing the exception occurs within a try
statement. - Identifies the type of exception being caught and
contains statements to describe, work around, or
fix the error.
61Exception Handling (cont)
- The finally statement is
- Optional and is always executed regardless of
whether an exception has taken place. - Placed after the catch statement.
- Note It all might sound complex, but it is
actually quite simple. - Examples on following slides
62Exception Handling (cont)
- // Author Mike O'Malley
- // Source File W04_03_Exception_Handling.java
- // Description Exception handling examples
(Console Application). - import javax.swing.JOptionPane // For Swing
Dialogs - public class W04_03_Exception_Handling
-
- public static void main (String args)
-
- // Handle division by zero and display an
error - // to the command window.
- try
-
- int i 100 / 0 // Division by zero.
-
- catch(ArithmeticException e)
-
- System.out.println ("\nError division
by zero.") -
COIT 11222 - Visual Programming Author(s) Mike
OMalley Slide 62
63Exception Handling (cont)
// Handle conversion when a string contains
invalid float data // and display an error
using a Swing Dialog. String In_String
"12ab.0" double Input_Value 0.0
try Input_Value
Double.parseDouble (In_String)
catch(NumberFormatException e)
JOptionPane.showMessageDialog (null,
"Error '" In_String "' could not be
converted " "to a floating point
number.", "Error",
JOptionPane.ERROR_MESSAGE)
COIT 11222 - Visual Programming Author(s) Mike
OMalley Slide 63
64Exception Handling (cont)
// Convert a string to float and range
check, so that the data // fails the range
check, and display any error to the command
// window and in a Swing Dialog. // Use
constants in range checking and error message so
that // the boundary values aren't
repeated in multiple places. String
In_String2 "12.0" double Input_Value2
0.0 final double MIN_VALUE 20.0
final double MAX_VALUE 100.0 try
Input_Value2 Double.parseDouble
(In_String2) if ((Input_Value2 lt
MIN_VALUE) (Input_Value2 gt MAX_VALUE))
throw new NumberFormatException()
COIT 11222 - Visual Programming Author(s) Mike
OMalley Slide 64
65Exception Handling (cont)
catch(NumberFormatException e)
String Error_Message "Error
'" In_String "' could not be converted to "
"a floating point number, or
value is not between " MIN_VALUE
" and " MAX_VALUE "."
System.out.println ("\n" Error_Message)
JOptionPane.showMessageDialog
(null, Error_Message, "Error", JOptionPane.ERROR_M
ESSAGE)
COIT 11222 - Visual Programming Author(s) Mike
OMalley Slide 65
66Exception Handling (cont)
- If our program was an Applet, then we could
display the error message in a Label, a Swing
Dialog or both, for example here we do both - catch(NumberFormatException e)
-
- String Error_Message
- "Error '" In_String "' could not be
converted to " - "a floating point number, or value is not
between " - MIN_VALUE " and " MAX_VALUE "."
- Output_Label.setText (Error_Message)
- JOptionPane.showMessageDialog
- (null, Error_Message, "Error",
JOptionPane.ERROR_MESSAGE)
COIT 11222 - Visual Programming Author(s) Mike
OMalley Slide 66
67User Defined Methods
- User Defined Methods are named blocks of code
that the user of the programming language (the
programmer) can call whenever they are needed. - In console applications, the main is a mandatory
method, but you can add as many User Defined
Methods you like. - In Applets, the init is a mandatory method, and
you also need paint, actionPerformed, etc
depending on what you are trying to achieve, but
once again you can add as many User Defined
Methods you like.
COIT 11222 - Visual Programming Author(s) Mike
OMalley Slide 67
68User Defined Methods (cont)
- User Defined Methods can be passed data
(integers, floats, Strings, etc) so that they can
do whatever processing is desired. - If a User Defined Method does not need to return
any data, then it is a void method. - If a User Defined Method need to return a value
of a specific type (integer, float, String, etc)
then it is declared to be of this type, and needs
to contain a return statement to return the
required value.
COIT 11222 - Visual Programming Author(s) Mike
OMalley Slide 68
69User Defined Methods (cont)
- Example 1 we need a method to accept a
products price or a service charge (excluding
GST) and calculate and display the GST and the
price including GST. - Like any method, we want to be able to call this
method whenever we need to, such as - Calculate_And_Display_GST (100.0)
- Calculate_And_Display_GST (25.0)
- Calculate_And_Display_GST (2999.99)
COIT 11222 - Visual Programming Author(s) Mike
OMalley Slide 69
70User Defined Methods (cont)
- Here, the method is displaying the data to the
Console Screen (we are running a Console
Application) - private static void Calculate_And_Display_GST
(double In_Amount_Excl_GST) -
- final double GST_RATE 10.0 / 100.0
- double GST_Amount In_Amount_Excl_GST
GST_RATE - double Amount_Incl_GST In_Amount_Excl_GST
GST_Amount - System.out.println ("\nAmount Excl GST "
In_Amount_Excl_GST) - System.out.println ("\n GST Amount "
GST_Amount) - System.out.println ("\n Amount Inc GST "
Amount_Incl_GST) - System.out.println ()
-
- Our method is returning no data so its type is
void.
COIT 11222 - Visual Programming Author(s) Mike
OMalley Slide 70
71User Defined Methods (cont)
- If we had an Applet and wanted to display the
output in one or more Labels, we could change the
method as follows - private static void Calculate_And_Display_GST
(double In_Amount_Excl_GST) -
- final double GST_RATE 10.0 / 100.0
- double GST_Amount In_Amount_Excl_GST
GST_RATE - double Amount_Incl_GST In_Amount_Excl_GST
GST_Amount - Out1_Label.setText (Amount Excl GST "
In_Amount_Excl_GST) - Out2_Label.setText ( GST Amount "
GST_Amount) - Out3_Label.setText ( Amount Inc GST "
Amount_Incl_GST) -
- Our method is returning no data so its type is
void.
COIT 11222 - Visual Programming Author(s) Mike
OMalley Slide 71
72User Defined Methods (cont)
- Example 2 Lets create a new method which
calculates and returns the GST without displaying
it to the screen. The calling program can then
do whatever it likes with the GST amount that is
returned. - Here, out Applet is displaying the value in a
Label - double GST_Amount 0.0
- GST_Amount Calculate_GST (100.0)
- Out_Label.setText ("GST Amount "
- GST_Amount)
COIT 11222 - Visual Programming Author(s) Mike
OMalley Slide 72
73User Defined Methods (cont)
- private double Calculate_GST (double
In_Amount_Excl_GST) -
- final double GST_RATE 10.0 / 100.0
- double GST_Amount In_Amount_Excl_GST
GST_RATE - return GST_Amount
-
- Our method is returning a double value so it is
of type double. - Our method returns the double value via the
return statement. - If our method is non-void, then it must contain a
return statement.
COIT 11222 - Visual Programming Author(s) Mike
OMalley Slide 73
74Public Vs Private - Methods
- Public methods are available for use by other
methods even those which are not in our class. - Some methods must be declared as public, such as
main, init, paint, actionPerformed, etc. - Private methods are only available for use other
methods in our class. - For example, if a method is not reusable, or
should not be callable by a method outside of our
class, then declare it as private. - Recommendation Declare all of the User Defined
Methods you create as private unless there is
good reason for them to be public. - See the User Defined Examples in the prior slides.
75Public Vs Private - Data
- Public class data is data that is accessible and
modifiable by other methods, even those which are
not in our class. - Private class data is data that is accessible and
modifiable only by class methods that is,
methods of the current class. - Recommendation Declare all class data as private
unless there is very good reason for it to be
public. - Examples on following slides
76Public Vs Private (cont)
public class W03_02_Wages_Calc__Applet ...
// Declare class data. private String
Emp_ID private int Hours, Rate
private double Gross_Pay etc
public void init() // Code for this
method goes here ... public void
actionPerformed (ActionEvent e) //
Code for this method goes here ...
COIT 11222 - Visual Programming Author(s) Mike
OMalley Slide 76
77Public Vs Private (cont)
public void paint (Graphics g) //
Code for this method goes here ...
private void Calculate_And_Display_GST (...)
// Code for this method goes here ...
private double Calculate_GST (...)
// Code for this method goes here ...
etc
COIT 11222 - Visual Programming Author(s) Mike
OMalley Slide 77
78Assignment 1 90
- You can now complete 90 of Assignment 1.
- Before you proceed with Assignment 1, make sure
you - Thoroughly read, review, and explore all topics
discussed in the lecture material for Weeks 1-4. - Do all of the tutorial questions for Weeks 1-4.
- Follow the Development Hints and Tips in the
assignment specification (Course Profile). - Students who tried to avoid these activities in
the past have found that the Assignment took them
far longer to finish !! e.g. 70 hours instead of
5 hours.
79Summary of Topics Covered
- More GUI Development logos, drawString,
colours, checkboxes, radio buttons, etc - Pseudo Code and Flowcharts
- UML and UML Class Diagrams
- Math class, random numbers, etc
- Exception handling
- User Defined Methods
- Public Vs Private
- Lots of topics this week (again).
- We've had to set a cracking pace to cover enough
to allow you to do Assignment 1. - Dont Panic next week the pace is easier (for a
while). - Assignment 1 90
80End of Lecture