liang, oreilly, herbert schildt, joseph o’neil, steven holzner, ibm corp advanced java programming...
Post on 27-Dec-2015
220 Views
Preview:
TRANSCRIPT
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner, IBM Corp
Advanced Java Programming
CSE 7345/5345/ NTU 531Session 7
Welcome Welcome Back!!!Back!!!
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner, IBM Corp
claurent@engr.smu.educlaurent@engr.smu.edu
Chantale Laurent-
Rice
Welcome Welcome Back!!!Back!!!
trice75447@aol.comtrice75447@aol.com
Office Hours:by appt3:30pm-4:30pmSIC 353
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner, IBM Corp
Short reviewPackages
• In Java, each class is defined in a single file called ClassName.java.
• A package is a name for a set of related classes,• Java uses package names to locate classes at
compile-time and at runtime.• Packages can be seen as some kind of libraries in
which the classes are grouped.• The difference is that packages provide an
additional scope.• Each class file must belong to a package:• Example:• Package dpack;• Package java.awt.event;
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner, IBM Corp
Packages con’t• If no package is given, the class is placed
in a default package with no name.• A compilation unit (a file) declares one or
more classes. It is a file that may contain several class declarations. It is used as an input for the java Compiler (javac) which outputs a series of class files (bytecodes).
• There is a class file for each class in the compilation unit.
• At the most one class is declared public.Example:
Source code: ClassName.java hello.javaBytecode: className.class hello.class
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner, IBM Corp
Packages con’t
• To use the classes, one or more modules in a program can import the entire package with the declaration, such as
import graphics.*;• The asterisk indicates to the
compiler that it should import all classes in the graphics package.
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner, IBM Corp
Standard packages• Java.applet- provides the means to create applet• Java.awt- provides class-based GUI with windows• Java.awt.*- have subpackages such as java.awt,color,
java.awt.font, and java.awt.image• Java.beans- provides basic elements for JavaBeans• Java.io- provides I/O• Java.lang- wrapper classes such as: Char, int, Double,
String and StringBuffer• java.math- math programmers• Java.net- network, socket handler, internet utility classes• Java.rmi- Remote Method Invocation provide support for
distributed code controlled by remote interface
• Java.security- implements security, encryption keys, and certificates
• Java.sql- implements of Structured Query Language database fields types and methods
• Java.text- provide parsers and formatters• Java.util- Java Application and applet (Random class,
Collection, list, Set) packages container class.• Java.util.jar- subpackage w/I java.util.• Java.util.zip- subpackage for .zip file compression format.
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner, IBM Corp
Packages con’t• To import just one class:
import graphics.Rectangle;• It is not correct to import the package itself:
import graphics;• Some packages provide one or more
subpackages, such as java.util.jar, a subpackage of java.util.
• Importing a package does not import any subpackages.
• You must do that explicitly using statements like these:
• Import java.utils.*;• Import java.utils.jar.*;
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner, IBM Corp
Small Quiz
• What happen if you tried to compile and run the following code?
1. public class EqualsTest{2. public static void main(String[] args){3. Long L = new Long( 7 );
4. if( L.equals( 7L))5. System.out.println(“Equal”);
else System.out.println(“Not Equal”);
6. }7. }
a. The program would compile and print “Equal”b. The program would compile and print “Not Equal”.c. The compiler would object to line 4.d. A runtime cast error would occur at line 4.
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner, IBM Corp
Small Quiz
C. qualsTest.java:5: cannot resolve symbolsymbol : method equals (long)location: class java.lang.Long
if( L.equals( 7L)) ^1 error• The compiler knows that the equals method
takes an Object rather than a primitive as input. Because the compiler does not compile answer a, b, d are incorrect.
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner, IBM Corp
Small Quiz• What happen if you tried to compile and
run the following code?
1. public class EqualsTest{2. public static void main(String[] args){3. Object A = new Long ( 7 );4. Long L = new Long( 7 );
5. if( A.equals( L ))
System.out.println(“Equal”);6. else System.out.println(“Not
Equal”);7. }8. }
a. The program would compile and print “Equal”b. The program would compile and print “Not Equal”.c. The compiler would object to line 5.d. A runtime cast error would occur at line 5.
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner, IBM Corp
Small Quiz
a. • Because the Long object created in line 3
does not lose its identity when cast to Object A, so the equals method knows the class is correct and compares the values.
• Answer c, d, do not occur because this is the correct form for comparing objects with the equals method. Therefore, they are incorrect.
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner, IBM Corp
What compile-time error is generated for the following program?
class D3 implements B {public void display() {
System.out.println("D3");}
}
class InterfaceRefVar{public static void main(String[] args){
B b;b = new D1();b.display();b = new D2();b.display();b = new D3();b.display();
}}
interface B{void display();
}
class D1{}
class D2 implements B{public void display() {
System.out.println("D2");}
}
interface
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner, IBM Corp
interfaceThe line “b = new D1();” generates an
error because the types are incompatible for assignment. Class D1 does not implements interface B.
• C:\InterfaceRefVar.java:23: incompatible types
• found : D1• required: B• b = new D1();• ^• 1 error
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner, IBM Corp
Chapter 10 Getting Started with GUI Programming
• GUI Class Hierarchy• Frames
– Creating frames, centering frames, adding components to frames
• Layout Managers – FlowLayout, GridLayout, BorderLayout
• Drawing on Panels– The paintComponent method
• Using Colors, Fonts, and Font Metrics• Drawing Geometric Figures
– Lines, Rectangles, Ovals, Arcs, and Polygons
• Event-Driven Programming– Event Source, Listener, Listener Interface
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner, IBM Corp
AWT/JFC • AWT was a powerful toolkit when introduced
– it was the original driving force behind Java’s popularity
– is today’s standard , a limited implementation
– not designed to provide a serious, main UI for the needs of many programmers.
• Now Swing, which has about four times the number of user interface (UI) components as the AWT – Swing is part of the standard Java
distribution
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner, IBM Corp
AWT (Optional)AWTEvent
Font
FontMetrics
Component
Graphics
Object Color
Canvas
Button
TextComponent
Label
List
CheckBoxGroup
CheckBox
Choice
Container Panel Applet
Frame
Dialog FileDialog
Window
TextField
TextArea
MenuComponent MenuItem
MenuBar
Menu
Scrollbar
LayoutManager
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner, IBM Corp
Question?
• Is JFC and Swing the same?
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner, IBM Corp
JFC
• Many programmer that that JFC and Swing are the same thing, but that’s not so; the JFC contains Swing and quite a number of other items.
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner, IBM Corp
What’s in JFC?
Swing- The large UI packageCut and paste- Clipboard supportAccessibility features- Aimed at users with
disabilities.The desktop Colors features- First
introduced in Java 1.1
Java2D- Improved color, image, and text support
Printing- Originally enabled in Java 1.1
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner, IBM Corp
What’s in Swing?Class DescriptionAbstractButton Abstract superclass for Swing
buttonsButtonGroup Encapsulates a mutually exclusive
set of buttonsImageIcon Encapsulates an iconJApplet The Swing version of AppletJButton The Swing push button classJCheckBox The Swing check box classJComboBox Encapsulates a combo boxJLabel The Swing version of a labelJRadioButton The Swing version of a radio button JScrollPane Encapsulates a scrollable windowJTable Encapsulates a table-based controlJTextField The Swing version of a text fieldJTree Encapsulates a tree-based control
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner, IBM Corp
GUI Class Hierarchy (Swing)
Dimension
Font
FontMetrics
Component
Graphics
Object Color
Container
Panel Applet
Frame
Dialog
Window
JComponent
JApplet
JFrame
JDialog
Swing Components in the javax.swing package
Lightweight
Heavyweight
Classes in the java.awt package
1
LayoutManager
*
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner, IBM Corp
JComponent
.
JButton
JMenuItem
JCheckBoxMenuItem
AbstractButton
JComponent
JMenu
JRadioButtonMenuItem
JToggleButton JCheckBox
JRadioButton
JComboBox
JInternalFrame JLayeredPane
JList JMenuBar JOptionPane
JPopupMenu
JProgressBar
JPane
JFileChooser
JScrollBar JScrollPane
JSeparator
JSplitPane
JSlider
JTabbedPane
JTable
JTableHeader
JTextField JTextComponent
JEditorPane
JTextArea
JToolBar
JToolTip
JTree
JRootPane
JPanel
JPasswordField
JColorChooser
JLabel
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner, IBM Corp
JApplets
• Fundamental to Swing is the JApplet class, which extends Applet.
• Applets that use Swing must be subclasses of JApplet.
• JApplet is rich with functionality that is not found in Applet.
• For Example:• JApplet support various “panes”, such
as the content pane, the glass pane, and the root pane.
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner, IBM Corp
Frames
• Frame is a window that is not contained inside another window. Frame is the basis to contain other user interface components in Java GUI applications.
• The Frame class can be used to create windows.
• For Swing GUI programs, use JFrame class to create widows.
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner, IBM Corp
UI Components
Frame Pull-down Menus
User InterfaceComponents (UI)
Panel
Panel
Panel
UI
Panel
UI
Panel
UI
Applet
Panel
User InterfaceComponents
Panel
User InterfaceComponents
Panel
User InterfaceComponents
Panel
User InterfaceComponents
panel
Pull-down Menus
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner, IBM Corp
Creating Frames
RunRun
import javax.swing.*;public class MyFrame { public static void main(String[] args) { JFrame frame = new JFrame("Test Frame"); frame.setSize(400, 300); frame.setVisible(true); frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE); }
}
NOTE: You must have JDK 1.3 or higher to run the slides.
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner, IBM Corp
Centering Frames
By default, a frame is displayed in the upper-left corner of the screen. To display a frame at a specified location, you can use the setLocation(x, y) method in the JFrame class. This method places the upper-left corner of a frame at location (x, y).
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner, IBM Corp
Centering Frames, cont.
RunRun
screenHeight
screenWidth
getHeight()
getWidth()
(x, y)
Frame
Screen
(0, 0)
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner, IBM Corp
Adding Components into a Frame
// Add a button into the frame frame.getContentPane().add( new JButton("OK"));
RunRun
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner, IBM Corp
NOTE
The content pane is a subclass of Container.
The statement in the preceding slide can be
replaced by the following two lines:
Container container =
frame.getContentPane();
container.add(new JButton("OK"));
You may wonder how a Container object is
created. It is created when a JFrame object
is created. A JFrame object uses the content
pane to hold components in the frame.
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner, IBM Corp
Layout Managers
• Java’s layout managers provide a level of abstraction to automatically map your user interface on all window systems.
• The UI components are placed in containers. Each container has a layout manager to arrange the UI components within the container.
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner, IBM Corp
Kinds of Layout Managers• FlowLayout (Chapter 10)
• GridLayout (Chapter 10)
• BorderLayout (Chapter 10)
• CardLayout (Chapter 12)
• GridBagLayout (Chapter 12)
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner, IBM Corp
Example 10.1Testing the FlowLayout Manager
The components are arranged in the container from left to right in the order in which they were added. When one row becomes filled, a new row is started.
RunRun
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner, IBM Corp
FlowLayout Constructors• public FlowLayout(int align, int hGap, int vGap)
Constructs a new FlowLayout with a specified alignment, horizontal gap, and vertical gap. The gaps are the distances inpixel between components.
• public FlowLayout(int alignment)
Constructs a new FlowLayout with a specified alignment and a default gap of five pixels for both horizontal and vertical.
• public FlowLayout()
Constructs a new FlowLayout with a defaultcenter alignment and a default gap of five pixelsfor both horizontal and vertical.
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner, IBM Corp
Example 10.2Testing the GridLayout Manager
The GridLayout manager arranges componentsin a grid (matrix) formation with the number ofrows and columns defined by the constructor. The components are placed in the grid from left to right starting with the first row, then the second, and so on.
RunRun
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner, IBM Corp
GridLayout Constructors• public GridLayout(int rows,int columns)Constructs a new GridLayout with the specified number of rows and columns.
• public GridLayout(int rows, int columns, int hGap, int vGap)Constructs a new GridLayout with thespecified number of rows and columns,along with specified horizontal andvertical gaps between components.
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner, IBM Corp
Example 10.3Testing the BorderLayout Manager
The BorderLayout manager divides the container into five areas: East, South, West, North, and Center. Components are added to a BorderLayout by using the add method.
RunRun
add(Component, constraint), where constraint is BorderLayout.EAST, BorderLayout.SOUTH, BorderLayout.WEST, BorderLayout.NORTH, or BorderLayout.CENTER.
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner, IBM Corp
Example 10.3, cont.
RunRun
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner, IBM Corp
Using Panels as Containers
• Panels act as smaller containers for grouping user interface components.
• It is recommended that you place the user interface components in panels and place the panels in a frame. You can also place panels in a panel.
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner, IBM Corp
Example 10.4 Testing Panel This example uses panels to organize components. The program creates a user interface for a Microwave oven.
RunRun
A button
A textfield
12
buttons
frame
p2
p1
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner, IBM Corp
Drawing on Panels
JPanel can be used to draw graphics (including text) and enable user interaction.
To draw in a panel, you create a new class that extends JPanel and override the paintComponent method to tell the panel how to draw things. You can then display strings, draw geometric shapes, and view images on the panel.
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner, IBM Corp
Drawing on Panels, cont.public class DrawMessage extends JPanel { /** Main method */ public static void main(String[] args) { JFrame frame = new JFrame("DrawMessage"); frame.getContentPane().add(new DrawMessage()); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(300, 200); frame.setVisible(true); } /** Paint the message */ public void paintComponent(Graphics g) { super.paintComponent(g); g.drawString("Welcome to Java!", 40, 40); }}
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner, IBM Corp
Drawing on Panels, cont.
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner, IBM Corp
NOTEThe Graphics class is an abstract class for displaying figures and images on the screen on different platforms.
The Graphics class is implemented on the native platform in the JVM. When you use the paintComponent method to draw things on a graphics context g, this g is an instance of a concrete subclass of the abstract Graphics class for the specific platform.
The Graphics class encapsulates the platform details and enables you to draw things uniformly without concerning specific platforms.
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner, IBM Corp
NOTEWhenever a component is displayed, a Graphics object is created for the component. The Swing components use the paintComponent method to draw things. The paintComponent method is automatically invoked to paint the graphics context when the component is first displayed or whenever the component needs to be redisplayed. Invoking super.paintComponent(g) is necessary to ensure that the viewing area is cleared before a new drawing is displayed.
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner, IBM Corp
NOTE
To draw things, normally you create a subclass of JPanel and override its paintComponent method to tell the system how to draw.
In fact, you can draw things on any GUI component.
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner, IBM Corp
The Color ClassYou can set colors for GUI components by using the java.awt.Color class. Colors are made of red, green, and blue components, each of which is represented by a byte value that describes its intensity, ranging from 0 (darkest shade) to 255 (lightest shade). This is known as the RGB model. Color c = new Color(r, g, b);r, g, and b specify a color by its red, green, and blue components.
Example:Color c = new Color(228, 100, 255);
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner, IBM Corp
Setting ColorsYou can use the following methods to set the component’s background and foreground colors:
setBackground(Color c)
setForeground(Color c)
Example:
setBackground(Color.yellow); setForeground(Color.red);
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner, IBM Corp
The Font Class
Font myFont = Font(name, style, size);
Example:Font myFont = new Font("SansSerif ", Font.BOLD, 16);Font myFont = new Font("Serif", Font.BOLD+Font.ITALIC, 12);
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner, IBM Corp
Finding All Available Font Names
GraphicsEnvironment e =
GraphicsEnvironment.getLocalGraphicsEnvironment();
String[] fontnames = e.getAvailableFontFamilyNames();
for (int i = 0; i < fontnames.length; i++)
System.out.println(fontnames[i]);
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner, IBM Corp
Setting Fontspublic void paint(Graphics g) {
Font myFont = new Font("Times", Font.BOLD, 16);
g.setFont(myFont);
g.drawString("Welcome to Java", 20, 40);
//set a new font
g.setFont(new Font("Courier", Font.BOLD+Font.ITALIC, 12));
g.drawString("Welcome to Java", 20, 70);
}
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner, IBM Corp
The FontMetrics Class
public void paint(Graphics g) {
g.getFontMetrics(Font f); or g.getFontMetrics();}
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner, IBM Corp
Get FontMetrics • public int getAscent()
• public int getDescent()
• public int getLeading()
• public int getHeight()
• public int stringWidth(String str)
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner, IBM Corp
Example 10.5Using FontMetrics
• Objective: Display “Welcome to Java” in SansSerif 20-point bold, centered in the frame.
RunRun
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner, IBM Corp
Welcome to Java stringWidth
stringAscent getHeight()
getWidth()
messagePanel
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner, IBM Corp
Example 10.5, cont.
MessagePanel -xCoordinate: int -yCoordinate: int -centered: boolean -message: String +getMessage(): String +getXCoordinate(): int +getYCoordinate(): int +isCentered(): boolean +setMessage(message: String): void +setXCoordinate(x: int): void +setYCoordinate(y: int): void +setCentered(centered: boolean): void +paintComponent(g: Graphics): void +getPerferredSize(): Dimension +getMinimumSize(): Dimension
1 TestFontMetrics
JPanel -char token +getToken +setToken +paintComponet +mouseClicked
JFrame -char token +getToken +setToken +paintComponet +mouseClicked
1
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner, IBM Corp
Drawing Geometric Figures
• Drawing Lines
• Drawing Rectangles
• Drawing Ovals
• Drawing Arcs
• Drawing Polygons
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner, IBM Corp
Drawing Lines
drawLine(x1, y1, x2, y2);
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner, IBM Corp
Drawing Rectangles
• drawRect(x, y, w, h);
• fillRect(x, y, w, h);
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner, IBM Corp
Drawing Rounded Rectangles
• drawRoundRect(x, y, w, h, aw, ah);
• fillRoundRect(x, y, w, h, aw, ah);
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner, IBM Corp
Drawing Ovals
• drawOval(x, y, w, h);
• fillOval(x, y, w, h);
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner, IBM Corp
Drawing Arcs• drawArc(x, y, w, h, angle1, angle2);• fillArc(x, y, w, h, angle1, angle2);
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner, IBM Corp
Drawing Polygons
int[] x = {40, 70, 60, 45, 20};int[] y = {20, 40, 80, 45, 60};g.drawPolygon(x, y, x.length);g.fillPolygon(x, y, x.length);
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner, IBM Corp
Example 10.6Drawing a Clock
• Objective: Use drawing and trigonometric methods to draw a clock showing the specified hour, minute, and second in a frame.
RunRun
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner, IBM Corp
Drawing ClockxEnd = xCenter + handLength sin()
yEnd = yCenter - handLength cos()Since there are sixty seconds in one minute, the angle for the second hand is
second (2/60)
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner, IBM Corp
Drawing Clock, cont.xEnd = xCenter + handLength sin()
yEnd = yCenter - handLength cos()The position of the minute hand is
determined by the minute and second. The exact minute value comined with seconds is minute + second/60. For example, if the time is 3 minutes and 30 seconds. The total minutes are 3.5. Since there are sixty minutes in one hour, the angle for the minute hand is (minute + second/60) (2/60)
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner, IBM Corp
Drawing Clock, cont.xEnd = xCenter + handLength sin()
yEnd = yCenter - handLength cos()Since one circle is divided into twelve hours, the angle for the hour hand is (hour + minute/60 + second/(60 60))) (2/12)
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner, IBM Corp
Event-Driven Programming
• Procedural programming is executed in procedural order.
• In event-driven programming, code is executed upon activation of events.
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner, IBM Corp
Events• An event can be defined as a type of
signal to the program that something has happened.
• The event is generated by external user actions such as mouse movements, mouse button clicks, and keystrokes, or by the operating system, such as a timer.
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner, IBM Corp
Event Information• id: A number that identifies the event. • target: The source component upon which the event
occurred. • arg: Additional information about the source
components. • x, y coordinates: The mouse pointer location when a
mouse movement event occurred.• clickCount: The number of consecutive clicks for the
mouse events. For other events, it is zero.• when: The time stamp of the event.• key: The key that was pressed or released.
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner, IBM Corp
Event Classes
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner, IBM Corp
Selected User Actions
Source Event TypeUser Action Object Generated
Clicked on a button JButton ActionEvent
Changed text JTextComponent TextEvent
Double-clicked on a list item JList ActionEvent
Selected or deselected an item JList ItemEvent with a single click
Selected or deselected an item JComboBox ItemEvent
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner, IBM Corp
The Delegation Model
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner, IBM Corp
Selected Event Handlers Event Class Listener Interface Listener Methods (Handlers)ActionEvent ActionListener actionPerformed(ActionEvent)ItemEvent ItemListener itemStateChanged(ItemEvent)WindowEvent WindowListener windowClosing(WindowEvent)
windowOpened(WindowEvent)windowIconified(WindowEvent)windowDeiconified(WindowEvent)windowClosed(WindowEvent)windowActivated(WindowEvent)windowDeactivated(WindowEvent)
ContainerEvent ContainerListener componentAdded(ContainerEvent)
componentRemoved(ContainerEvent)
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner, IBM Corp
Example 10.7Handling Simple Action Events
• Objective: Display two buttons OK and Cancel in the window. A message is displayed on the console to indicate which button is clicked, when a button is clicked.
RunRun
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner, IBM Corp
Example 10.8Handling Window Events
RunRun
Objective: Demonstrate handling the window events. Any subclass of the Window class can generate the following window events: window opened, closing, closed, activated, deactivated, iconified, and deiconified. This program creates a frame, listens to the window events, and displays a message to indicate the occurring event.
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner, IBM Corp
Example 10.9 Multiple Listeners for a Single Source
RunRun
Objective: This example modifies Example 10.7 to add a new listener for each button. The two buttons OK and Cancel use the frame class as the listner. This example creates a new listener class as an additional listener for the action events on the buttons. When a button is clicked, both listeners respond to the action event.
top related