java lecture slides
TRANSCRIPT
8/11/2019 JAVA Lecture Slides
http://slidepdf.com/reader/full/java-lecture-slides 1/54
ICT 314 ADVANCED JAVA TECHNOLOGY
Instructor: r d appiah
8/11/2019 JAVA Lecture Slides
http://slidepdf.com/reader/full/java-lecture-slides 2/54
R D Appiah
Introduction: Building User Interfaces
In the earlier versions of Java, the building of graphical
user interfaces is usually achieved through the use of
a set of classes called the Abstract Windowing Toolkit
(AWT)
In this course, we will learn the use of the javax.swingpackage to create and design user interfaces.
This will be followed by the skills to arrange all of the
components on a user interface
And finally, learning to make user interface(s)
responsive to user control(s).
8/11/2019 JAVA Lecture Slides
http://slidepdf.com/reader/full/java-lecture-slides 3/54
R D Appiah
The Abstract Windowing Toolkit
This is a set of classes that enables you to
create a graphical user interface and receiveuser input from the mouse and keyboard.
Because Java is a platform-independent
language, the AWT offers a way to design aninterface that will have the same general
appearance and functionality on all systems it
runs on.
However, it is always advised that developers
must test their AWT-based interfaces on as
many platforms and browsers as possible.
8/11/2019 JAVA Lecture Slides
http://slidepdf.com/reader/full/java-lecture-slides 4/54
R D Appiah
The components of a GUI:
An interface created based on GUI may consist
of three basic things:Components: Anything that can be put onto a
user interface, including clickable buttons,
scrolling lists, pop-up menus, check boxes, andtext fields.
Containers: A component that can contain
other components. These may include suchthings as an Applet window, Panels, Dialog
boxes, and other standalone windows.
8/11/2019 JAVA Lecture Slides
http://slidepdf.com/reader/full/java-lecture-slides 5/54
R D Appiah
Layout Managers: These are objects that
define how the components in a container will
be arranged. Normally, one does not see alayout manager in an interface, but rather the
results of its action(s).
The AWT’s classes are all available within the java.awt.* package.
Thus, to make all of its resources available in a
programme, one has to add the following importstatement at the top of the source codes:
import java.awt.*;
8/11/2019 JAVA Lecture Slides
http://slidepdf.com/reader/full/java-lecture-slides 6/54
R D Appiah
The user-interface Components:
Components are placed onto a user interface
by adding them to a container.
Note also that a container is itself a component
and can be added to other containers – thus acontainer within a container.
To a higher extent, we will use both the
java.awt.* and javax.swing.* packages to designuser interfaces.
8/11/2019 JAVA Lecture Slides
http://slidepdf.com/reader/full/java-lecture-slides 7/54
R D Appiah
Steps:
A component is added to a container via the
following two steps:• Create the component of interest and
• Call the container’s add( ) method with the
component.
8/11/2019 JAVA Lecture Slides
http://slidepdf.com/reader/full/java-lecture-slides 8/54
R D Appiah
GUI I/O WITH JOptionPane
The JOptionPane class is used to provide
simple GUI-based input and output interfaces.It is important to note that the JOptionPane
class support only a string input.
Thus, to input a numerical value, we need to
perform the string conversion ourselves.
To achieve this, Java provides a feature calledwrapper classes and their corresponding
conversion methods, as follows:
8/11/2019 JAVA Lecture Slides
http://slidepdf.com/reader/full/java-lecture-slides 9/54
R D Appiah
Common wrapper classes and their
conversion methods:
Class Method Example
Integer parseInt Integer.parseInt(“45”)
-> 45
Long parseLong Long.parseLong(“45”)
-> 45L
Float parseFloat Float.parseFloat(“45.8”)
-> 45.8F
Double parseDouble Double.parseDouble(“45”
) -> 45.0
8/11/2019 JAVA Lecture Slides
http://slidepdf.com/reader/full/java-lecture-slides 10/54
R D Appiah
Customizing Frame Windows
Creating a customized user interface involves
defining a subclass of the JFrame class.The JFrame class contains the most
rudimentary functionalities to support features
found in any frame window, such asminimizing, moving and resizing the window.
For practical programming reasons, we
normally define a subclass of the JFrame classand add methods and data members to
implement the needed functionalities.
8/11/2019 JAVA Lecture Slides
http://slidepdf.com/reader/full/java-lecture-slides 11/54
R D Appiah
Illustration:
Refer to Ex6DefaultJFrame.java
To define a subclass of another class, wedeclare the subclass with the reserved word
extends.
To illustrate this, refer to Ex7JFrameSubclass.java
Notice that we declared the variable
contentPane in the changeBackColor() methodas a Container. We do not have a class called
ContentPane.
8/11/2019 JAVA Lecture Slides
http://slidepdf.com/reader/full/java-lecture-slides 12/54
R D Appiah
Button Placement
Refer to Ex9JButtonFrame.java
The type of button we use here is called apushbutton.
To use a button in a programme, we create an
instance of the javax.swing.JButton class.
We declare and create these buttons in the
following manner:
import javax.swing.*;
…JButton cancelButton, okButton;
cancelButton = new JButton(“CANCEL”);
okButton = new JButton(“OK”);
8/11/2019 JAVA Lecture Slides
http://slidepdf.com/reader/full/java-lecture-slides 13/54
R D Appiah
Setting The Layout
In Ex9JButtonFrame.java, we use the simplest
layout manager called FlowLayout.Here, we use the FlowLayout manager - which
places GUI objects in a top-to-buttom, left-to-
right order.Placing GUI objects on the content pane by
explicitly specifying their position and size is
known as absolute positioning.
We will discuss other common layout managers
and absolute positioning in later parts of the
course.
8/11/2019 JAVA Lecture Slides
http://slidepdf.com/reader/full/java-lecture-slides 14/54
R D Appiah
Handling Events
An action, such as clicking a button is called an
event; and the mechanism to process theevents is called event handling.
The event-handling model of Java is based on
the concept known as the delegation based
event model.
With this model, event handling involves two
types of Objects:• event source objects and
• event listener objects.
8/11/2019 JAVA Lecture Slides
http://slidepdf.com/reader/full/java-lecture-slides 15/54
R D Appiah
A GUI object, such as a button, where the event
occurs is called the event source – and we say
an event source generates events.
When an event is generated, the system
notifies the relevant event listener object or
simply an event listener.
An event listener is an object that includes a
method that gets executed in response to
generated events.In Java, it is possible for a single object to be
both an event source and an event listener.
8/11/2019 JAVA Lecture Slides
http://slidepdf.com/reader/full/java-lecture-slides 16/54
R D Appiah
One of the most commonly used events in Java
is called an action event.
For example, when a button is clicked or amenu item is selected, an event source will
generate an action event.
For the generated events to be processed, wemust associate, or register , event listeners to
the event sources.
If the event sources have no registeredlisteners, then generated events are simply
ignored.
8/11/2019 JAVA Lecture Slides
http://slidepdf.com/reader/full/java-lecture-slides 17/54
R D Appiah
An object that can be registered as an action
listener must be an instance of a class that is
declared specifically for the purpose.
Such classes are called action listener
classes.
Thus, an object created from an action listener
class becomes an action listener object.
An action listener is associated to an action
event source by calling the source’s
addActionListener() method.This is done by passing the action listener as
an argument in the process.
8/11/2019 JAVA Lecture Slides
http://slidepdf.com/reader/full/java-lecture-slides 18/54
R D Appiah
Example:
To register an instance of ButtonHandler as an
action listener of okButton and cancelButton,we execute the following code:
ButtonHandler handler = new ButtonHanler( );
okButton.addActionListener(handler);cancelButton.addActionListener(handler);
Note that we are associating a single listener tomultiple event sources; and multiple listeners
can also be associated to a single event source.
8/11/2019 JAVA Lecture Slides
http://slidepdf.com/reader/full/java-lecture-slides 19/54
8/11/2019 JAVA Lecture Slides
http://slidepdf.com/reader/full/java-lecture-slides 20/54
R D Appiah
As an example, refer to
Ex11ButtonFrameHandler.java
An Interface: An interface is a collection of methods that
indicate a class has some behaviour in addition
to what it inherits from its superclasses.They are said to be templates of behaviour that
other classes are expected to implement.
Interfaces serve as reference data types – these include constants and abstract
methods.
8/11/2019 JAVA Lecture Slides
http://slidepdf.com/reader/full/java-lecture-slides 21/54
R D Appiah
An abstract method has only the method
header ( or more formally, the method
prototype) – that is a method that has no body.
Trial Questions – Quick Checks:
1. What is the purpose of a layout manager?
2. Which object generates events? Which objectprocesses events?
3. What method must be implemented by a class that
implements the ActionListener interface?
4. What does the getActionCommand method of the ActionEvent class return?
5. What are interfaces used for in Java
programming?
8/11/2019 JAVA Lecture Slides
http://slidepdf.com/reader/full/java-lecture-slides 22/54
R D Appiah
Text-Related GUI Components
JLabel, JTextField and JTextArea
JLabel and JTextField deal with a single line of textwhile the JTextArea deals with multiple lines of text.
JTextField
Like a JButton object, an instance ofJTextField generates an action event when the
user presses the Enter key while the object is
active.We handle the JTextField object and register
its action listener much the same way as we
did for the JButton class.
8/11/2019 JAVA Lecture Slides
http://slidepdf.com/reader/full/java-lecture-slides 23/54
R D Appiah
Thus, in the declaration part, we add:
JTextField myTextField;
And in the constructor we create a JTextFieldobject and register the frame as its action
listener, as follows:
public Ex12TextFrame ( ){…
myTextField = new JTextField();
myTextField.setColums(22);
add(myTextField);myTextField.addActionListener(this);
…
8/11/2019 JAVA Lecture Slides
http://slidepdf.com/reader/full/java-lecture-slides 24/54
R D Appiah
After this stage, we are ready to modify the
actionPerformed method to handle both the
Button click events and the Enter key events.
In this case we have three event sources (two
buttons and one text field), and so we first
have to determine the source within the
actionPerformed method.
We use the instanceof operator to determine
the class to which the event source belongs.
We will also use the getText( ) method of the
JTextField class to retrieve the text that the
user has entered.
8/11/2019 JAVA Lecture Slides
http://slidepdf.com/reader/full/java-lecture-slides 25/54
R D Appiah
The complete method looks like:
public void actionPerformed(ActionEvent event) {
if(event.getSource( ) instanceof JButton) {
JButton clickedButton = (JButton) event.getSource( );
String buttonText = clickedButton.getText( );
setTitle(“You Clicke ” + buttonText);
} else { // the event source is inputLinesetTitle(“You Entered ‘ ” + inputLine.getText( ) + “ ’ ”);
}
}
8/11/2019 JAVA Lecture Slides
http://slidepdf.com/reader/full/java-lecture-slides 26/54
R D Appiah
Adding a JLabel Object:
A JLabel object is useful in displaying a label
that explains the purpose of the text field.
We will modify the Ex12TextFrame class by
placing a JLabel “PLEASE ENTER YOUR
NAME” above the text field.
Thus, we will add a data member declaration:
private JLabel prompt;We then create the object in the constructor as:
8/11/2019 JAVA Lecture Slides
http://slidepdf.com/reader/full/java-lecture-slides 27/54
R D Appiah
public Ex13TextFrame {
…
prompt = new JLabel ( );
prompt.setText(“PLEASE ENTER YOU NAME”);prompt.setSize(150, 25);
contentPane.add(prompt);
…
}
We can also set the text at the time of objectcreation as:
prompt = new JLabel (“PLEASE ENTER YOUR
NAME”);
Refer to Ex13TextFrame.java for an example.
8/11/2019 JAVA Lecture Slides
http://slidepdf.com/reader/full/java-lecture-slides 28/54
R D Appiah
The ImageIcon Object
We can also use the JLabel class to display
images.
To display an image, we pass an ImageIcon
object when we create a JLabel object instead
of a string.
To create this ImageIcon object, we must
specify the filename of an image.
We can add the data member declaration and
add an image jack.jpg, as follows:
8/11/2019 JAVA Lecture Slides
http://slidepdf.com/reader/full/java-lecture-slides 29/54
R D Appiah
private JLabel image;
public Ex14TextFrame {
…image = new JLabel (new ImageIcon (“jack.jpg” ) );
image.setSize(50,50);
contentPane.add(image);
…
}
For an example, refer to Ex14TextFrame.java
8/11/2019 JAVA Lecture Slides
http://slidepdf.com/reader/full/java-lecture-slides 30/54
R D Appiah
The JTextArea Object
Here, we declare a JTextArea object in the data
member section of the programmeEx15TextArea.java, as follows:
private JTextArea textArea;
textArea = new JTextArea( );textArea.setColumns(22);
textArea.setRows(8);
textArea.setBorder(
BorderFactory.createLineBorder(Color.RED) );textArea.setEditable(false);
contentPane.add(textArea);
Using The JScrollPane To Add Scroll Bars
8/11/2019 JAVA Lecture Slides
http://slidepdf.com/reader/full/java-lecture-slides 31/54
R D Appiah
Using The JScrollPane To Add Scroll Bars
Automatically.
Adding scroll bars that will appear automatically
when needed, we replace the statement:
contentPane.add(textArea);
of Ex15TextArea.java with the following codes:
JScollPane scrollText = new JScrollPane(textArea);
scrollText.setSize(200, 140);contentPane.add(scrollText);
For the complete programme, refer to
Ex15TextAreaScroll.java
LAYOUT MANAGERS
8/11/2019 JAVA Lecture Slides
http://slidepdf.com/reader/full/java-lecture-slides 32/54
R D Appiah
LAYOUT MANAGERS
The three major layout managers in use are
The java.awt.FlowLayout Manager. The java.awt.BorderLayout Manager.
The java.awt.GridLayout Manager.
The java.awt.BorderLayout Manager
This layout manager divides the container into
five regions:Center; North; South; East; and
West.
E l
8/11/2019 JAVA Lecture Slides
http://slidepdf.com/reader/full/java-lecture-slides 33/54
R D Appiah
Example:
The following set the contentPane’s layout and
then add five buttons to the container:contentPane.setLayout(new BorderLayout(20, 10 ) );
contentPane.add(button1, BorderLayout.NORTH);contentPane.add(button2, BorderLayout.SOUTH);
contentPane.add(button3, BorderLayout.EAST);
contentPane.add(button4, BorderLayout.WEST);
contentPane.add(button5, BorderLayout.CENTER);Refer to Ex16BorderLayout.java for an
illustrative example.
Th j t G idL t M
8/11/2019 JAVA Lecture Slides
http://slidepdf.com/reader/full/java-lecture-slides 34/54
R D Appiah
The java.awt.GridLayout Manager:
This places GUI components on equal-size N X
M grids.Before using the grid layout, one needs to
create a GridLayout object.
To create a GridLayout object, we pass twoarguments, representing the number of rows,
and the number of columns. For example:
contentPane.setLayout(new GridLayout(2, 3));
Note that, here components are placed in top-
to-bottom, left-to-right order.
R f t E 17G idL t j f l
8/11/2019 JAVA Lecture Slides
http://slidepdf.com/reader/full/java-lecture-slides 35/54
R D Appiah
Refer to Ex17GridLayout.java for an example.
Absolute Positioning
It is also possible not to use any layoutmanager – in which case we must explicitly
specify the position and size of the component
to be placed on the container.
We refer to the above approach as absolute
positioning.
You must note that to build attractive and
practical GUI-based Java programmers, one
must learn how to use layout managers
effectively.
T b l t iti i t th l t
8/11/2019 JAVA Lecture Slides
http://slidepdf.com/reader/full/java-lecture-slides 36/54
R D Appiah
To use absolute positioning, we set the layout
manager of a frame’s content pane to none by
passing null to the setLayout method, as
shown bolow:
contentPane.setLayout ( null ) ;
After this, and in the case of a button, we callthe setBounds method from the JButton class to
help us place the button at the desired location
and also to set the button to the desired size, asfollows:
clearButton.setBounds (75, 130, 80, 35) ;
R f t E 18Ab l t P j f
8/11/2019 JAVA Lecture Slides
http://slidepdf.com/reader/full/java-lecture-slides 37/54
R D Appiah
Refer to Ex18AbsolutePos.java for an
example.
Effective Use of Nested PanelsFor practical programming purposes, it is
common to see a combination of different layout
managers in the same programme.
Refer to Ex19NestedPanels.java and
Ex20NestedPanels.java for examples on
nested panels.
JCheckBo and JRadioB tton
8/11/2019 JAVA Lecture Slides
http://slidepdf.com/reader/full/java-lecture-slides 38/54
R D Appiah
JCheckBox and JRadioButton
Compared with the JButton class which
represents a type of button called a
pushbutton, the other two common types of
buttons are called check-boxes and radio
buttons.
For illustrative examples of check-boxes, refer
to Ex19JCheckBox1.java, Ex19CheckBox2.
For illustrative examples of radio buttons, refer
to Ex20JRadioButton.java.
8/11/2019 JAVA Lecture Slides
http://slidepdf.com/reader/full/java-lecture-slides 39/54
R D Appiah
JCheckBox and JRadioButton Classes
Compared with the JButton class which
represents a type of button called a
pushbutton, the other two common types of
buttons are called check-boxes and radio
buttons.
For illustrative examples of check-boxes, refer
to Ex19JCheckBox1.java, Ex19CheckBox2.
For illustrative examples of radio buttons, refer
to Ex20JRadioButton.java.
Th JC b B Cl
8/11/2019 JAVA Lecture Slides
http://slidepdf.com/reader/full/java-lecture-slides 40/54
R D Appiah
The JComboBox Class
The JComboBox class represents a combo box.
This class is similar to the JRadioButton class inthat is also allows the user to select an item
from a list of possible choices.
The basic difference between the two lies inhow the choices are presented to the user. It is
also referred to as Drop Down List.
Refer to Ex21JComboBox.java for anillustrative example.
Th JLi t Cl
8/11/2019 JAVA Lecture Slides
http://slidepdf.com/reader/full/java-lecture-slides 41/54
R D Appiah
The JList Class
The JList class is useful when we need to
display a list of items like: a list of students;a list of files; and so forth.
A JList object is constructed by passing an
array of String object to the JList constructor.Example:
String names = {“James”, “Adams”, “Joel”,
“Mercy”, ‘Joyce”, “Paul” };JList list = new JList (names);
With JLi t h ti f if i
8/11/2019 JAVA Lecture Slides
http://slidepdf.com/reader/full/java-lecture-slides 42/54
R D Appiah
With JList we have an option of specifying one
of the three selection modes:
1. Single Selection2. Single Interval
3. Multiple Interval.
The single selection mode allows the user toselect only one item at a time.
The single interval mode allows the user to
select a single contiguous interval.The multiple interval mode allows the user to
select multiple contiguous intervals (each
interval will include one or more items).
N ll th lti l i t l d i th
8/11/2019 JAVA Lecture Slides
http://slidepdf.com/reader/full/java-lecture-slides 43/54
R D Appiah
Normally, the multiple interval mode is the
default mode. The following three statements
show how to set the three selection modes:
list.setSelectionMode(
ListSelectionModel.SINGLE_SELECTION);
list.setSelectionMode(
ListSelectionModel.SINGLE_INTERVAL_SELECTION);
list.setSelectionMode(
ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
F ill t ti l f t
8/11/2019 JAVA Lecture Slides
http://slidepdf.com/reader/full/java-lecture-slides 44/54
R D Appiah
For an illustrative example, refer to
Ex22JList.java
Th JSlid Cl
8/11/2019 JAVA Lecture Slides
http://slidepdf.com/reader/full/java-lecture-slides 45/54
R D Appiah
The JSlider Class
The JSlider class represents a slider in which
the user can move a nob to a desired position,and the position of the nob at any time
determines the selected value.
Sliders are created and initialized in the
following manner:
JSlider slider = new JSlider( );
slider.setOrientation(JSlider.VERTICAL);
slider.setPaintLabels(true); // show tick mark labels
slider.setPaintTicks(true); // show tick marks
slider.setMinimum(MIN_COLOR);
lid tM i (MAX COLOR)
8/11/2019 JAVA Lecture Slides
http://slidepdf.com/reader/full/java-lecture-slides 46/54
R D Appiah
slider.setMaximum(MAX_COLOR);
slider.setValue(MAX_COLOR); //nob’s initial position
slider.setMajorTickSpacing(50);
slider.setMinorTickSpacing(25);
When a nob is moved, a JSlider object
generates a change event – this event occurs
when there is a change in the event source,
such as when the nob is moved.
To process change events, we must registerchange event listeners to a JSlider event source
object.
The class that implements the ChangeListener
8/11/2019 JAVA Lecture Slides
http://slidepdf.com/reader/full/java-lecture-slides 47/54
R D Appiah
The class that implements the ChangeListener
interface must define a method called
stateChanged, whose parameter is an instance
of ChangeEvent.
As an example, lets consider a Java
programme that behaves in such a way that
whenever a change event is generated, we
read the value from each slider and set the
background colour of a panel to a designated
colour.The stateChanged method will have the
following body:
int R G B;
8/11/2019 JAVA Lecture Slides
http://slidepdf.com/reader/full/java-lecture-slides 48/54
R D Appiah
int R, G, B;
R = redSlider.getValue( );
G = greenSlider.getValue( );
B = blueSlider.getValue( );
colorPanel.setBackground(new Color(R,G,B));
The values of R,G,B range between 0 and 255
inclusively.
For the full code listing of the programme, referto Ex23JSliderSample.java
Menus in Java
8/11/2019 JAVA Lecture Slides
http://slidepdf.com/reader/full/java-lecture-slides 49/54
R D Appiah
Menus in Java
Menus are used to support graphical user
interfaces.
In this section, we will describe how to display
menus and process menu events by using
JMenu, JMenuItem and JMenuBar from the
javax.swing package.
Steps in creating and adding menu items:
1. Create a JMenuBar object and attach it to a
frame.
2. Create a JMenu object.
3 Create JMenuItem objects and add them to
8/11/2019 JAVA Lecture Slides
http://slidepdf.com/reader/full/java-lecture-slides 50/54
R D Appiah
3. Create JMenuItem objects and add them to
the JMenu object.
4. Attach the JMenu object to the JMenuBar object.
Lets create two JMenu object: fileMenu and
editMenu.
fileMenu = new JMenu(“File”);
We then create and add a menu item “New” tofileMenu, as follows:
item = new JMenuItem(“New”);
8/11/2019 JAVA Lecture Slides
http://slidepdf.com/reader/full/java-lecture-slides 51/54
R D Appiah
item = new JMenuItem( New );
item.addActionListener(this);
fileMenu.add(item);
We repeat this sequence for all other items.
Note also that menu items are placed from the
top in the other they are added to the menu.
We can also include a horizontal line as a
separator between menu items by calling the
menu’s addSeparator method:
fileMenu.addSeparator( );
After the menus and their menu items are
8/11/2019 JAVA Lecture Slides
http://slidepdf.com/reader/full/java-lecture-slides 52/54
R D Appiah
After the menus and their menu items are
created, we attach them to a menu bar. We do
this in the constructor, where we create a
JMenuBar object, attach it to the frame by
calling the frame’s setMenuBar method, as
follows:
JMenuBar menuBar = new JMenuBar( );setMenuBar(menuBar); // attach it to the frame
menuBar.add(fileMenu);
menuBar.add(editMenu);We then show how to display which menu item
was selected, by using a JLabel object
response. We add response to the frame by:
response = new JLabel (“Hello This is Your Tester”);
8/11/2019 JAVA Lecture Slides
http://slidepdf.com/reader/full/java-lecture-slides 53/54
R D Appiah
response = new JLabel (“Hello, This is Your Tester”);
response.setSize(250, 50);
contentPane.add(response);
When a menu item is selected, the registered
action listener’s actionPerformed method is
called. Consider the following:
String menuName;
menuName = event.getActionCommand ( );
if (menuName.equals (“ Quit” ) ) {
System.exit (0);
} else {
response.setText(“ Menu Item ” + menuName + “ is Selected “ );
}
For an illustrative example refer to
8/11/2019 JAVA Lecture Slides
http://slidepdf.com/reader/full/java-lecture-slides 54/54
For an illustrative example, refer to
Ex24JMenuFrame.java
Handling Mouse EventsIn this section, we will describe the handling of
mouse events. In general, mouse events
include such user interactions as moving themouse, dragging the mouse and clicking the
mouse buttons.
For an illustrative example, refer toEx25TrackMouseFrame.java