Graphics programming-Frame-Components-working with 2D shapes-Using color, fonts, and images-Basics of event Handling-event handlers-adapter classes-actions mouse events-AWT
PackialathaVISTAS
12 views
78 slides
Aug 31, 2025
Slide 1 of 78
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
About This Presentation
Graphics programming-Frame-Components-working
with 2D shapes-Using color, fonts, and images-Basics
of event Handling-event handlers-adapter
classes-actions mouse events-AWT
Size: 825.01 KB
Language: en
Added: Aug 31, 2025
Slides: 78 pages
Slide Content
UNIT - V EVENT DRIVEN PROGRAMMING
Graphics programming-Frame-Components-working with 2D shapes-Using color , fonts, and images-Basics of event Handling-event handlers-adapter classes-actions mouse events-AWT event hierarchy-Introduction to Swing-layout management-Swing Components-Text Fields, Text Areas-Buttons-Check Boxes-Radio Buttons-Lists-choices-Scrollbars-windows-Menus-Dialog Boxes and Interfaces, Exception handling, Multithreaded programming, Strings, Input/output
Graphics programming Java supports for graphics that enable programmers to visually enhance applications Java contains many more sophisticated drawing capabilities as part of the Java 2D API
java.awt.Graphics class The java.awt.Graphics class provides many methods for graphics programming. A graphics context is encapsulated by the Graphics class and is obtained in two ways: • It is passed to an applet when one of its various methods, such as paint( ) or update( ) is called. • It is returned by the getGraphics ( ) method of Component.
GraphicsDemo.java import java.applet.Applet ; import java.awt.*; public class GraphicsDemo extends Applet{ public void paint(Graphics g){ g.setColor ( Color.red ); // set font color g.drawString (“Welcome”,50, 50); // display text g.drawLine (120,120,200,300); // draw a line // draw and fill rectangle g.drawRect (170,100,60,50); g.fillRect (170,100,60,50); // draw and fill rounded rectangle g.drawRoundRect (190, 10, 60, 50, 15, 15); g.fillRoundRect (190, 10, 60, 50, 15, 15);
// draw and fill oval g.drawOval (70,200,50,50); g.setColor ( Color.green ); g.fillOval (170,200,50,50); // draw and fill arc g.drawArc (90,150,70,70,0,75); g.fillArc (270,150,70,70,0,75); // draw a polygon int xpoints [] = {30, 200, 30, 200, 30}; int ypoints [] = {30, 30, 200, 200, 30}; int num = 5; g.drawPolygon ( xpoints , ypoints , num); } }
Frames A Frame is a top-level window with a title and a border. Frames are capable of generating the following types of window events: WindowOpened , WindowClosing , WindowClosed , WindowIconified , WindowDeiconified , WindowActivated , WindowDeactivated . Frame Constructor Frame() Constructs a new instance of Frame that is initially invisible. Frame(String) Constructs a new, initially invisible Frame object with the specified title
import java.awt.*; public class AwtFrame { public static void main(String[] args ){ Frame frm = new Frame(“Java AWT Frame”); Label lbl = new Label(“ Welcome”,Label.CENTER ); frm.add ( lbl ); frm.setSize (400,400); frm.setVisible (true); } }
Colors in Java To support different colors Java package comes with the Color class
import java.awt.*; import java.applet .*; /* <applet code=” ColorDemo ” width=350 height=300> </applet> */ public class ColorDemo extends Applet { public void init() { setBackground ( Color.CYAN ); } public void paint(Graphics g) { g.setColor ( Color.red ); // predefined color g.drawRect (50, 100, 150, 100); // rectangle outline is red color Color clr = new Color (200, 100, 150); g.setColor ( clr ); g.fillRect (220,100, 150, 100); // rectangle filled with clr color } }
BASICS OF EVENT HANDLING Event handling concept is quite simple: a source generates an event and sends it to one or more listeners. Listener simply waits until it receives an event. Once received, the listener processes the event and then returns. Events An event is an object that describes a state change in a source. Event Sources A source is an object that generates an event.
Events in java are included in the following packages: Java.util Java.awt Java.awt.event
Delegation event model: Defines the standard and consistent mechanism for a source to generate an event and send it to a set of listener. An object intrested to receive message is called an event listener. An object that generates the message is event source. SOURCE LISTENER LISTENER LISTENER
Participants of event delegation model: Event source Event listeners Event object Control flow of event delegation model: Event source Event listener Fires an event object 1 2 3 Source registers to listeners Reacts to event
Working of event handling: A listener object is a instance of a class that implements a special interface called listener interface. An event source is an object that can register listener objects and send them event objects. The event source sends event objects to all registered listeners when an event occurs. The listener object will then use the information in the event object to determine its reaction to event.
How Events are handled ? A source generates an Event and send it to one or more listeners registered with the source. Once event is received by the listener, they process the event and then return. Events are supported by a number of Java packages, like java.util , java.awt and java.awt.event .
Key Listener: package Listener; import java.awt.event.KeyEvent ; import java.awt.event.KeyListener ; import javax.swing.JFrame ; import javax.swing.JTextField ; public class KeyEventDemo implements KeyListener { public KeyEventDemo (){ JFrame s=new JFrame (" hai "); JTextField typingArea = new JTextField (20); typingArea.addKeyListener (this); s.add ( typingArea ); s.setVisible (true); } public void keyTyped ( KeyEvent e) { System.out.println (" KeyTyped ");} public void keyPressed ( KeyEvent e) { System.out.println (" KeyPressed ");} public void keyReleased ( KeyEvent e) { System.out.println (" Keyreleased ");} public static void main(String g[]) { KeyEventDemo a=new KeyEventDemo (); }}
ADAPTER CLASSES The AWT provides a number of adapter classes for the different event listener interfaces. ComponentAdapter ContainerAdapter FocusAdapter KeyAdapter MouseAdapter MouseMotionAdapter WindowAdapter
Java Language rule are such that we must implement all the methods of an interface even if we put them into empty braces.i.e. we must override all the methods declared in the interface. But we can create our classes as subclasses of one of the adapter classes, then we need to override only some of the methods we need. i.e, An adapter classes provide empty implementation of all methods declared in an EventListener interface.
Each adapter class implements the corresponding interface with a series of do-nothing methods. For example, MouseListener declares these five methods: public abstract void mouseClicked ( MouseEvent evt ) public abstract void mousePressed ( MouseEvent evt ) public abstract void mouseReleased ( MouseEvent evt ) public abstract void mouseEntered ( MouseEvent evt ) public abstract void mouseExited ( MouseEvent evt )
Therefore, MouseAdapter looks like this: package java.awt.event; import java.awt.*; import java.awt.event.*; public class MouseAdapter implementsMouseListener { public void mouseClicked(MouseEvent evt) {} public void mousePressed(MouseEvent evt) {} public void mouseReleased(MouseEvent evt) {} public void mouseEntered(MouseEvent evt) {} public void mouseExited(MouseEvent evt) {} }
E.g., WindowListener, have many methods: public void windowOpened(WindowEvent e) public void windowIconified(WindowEvent e) public void windowDeiconified(WindowEvent e) public void windowClosed(WindowEvent e) public void windowActivated(WindowEvent e) public void windowDeactivated(WindowEvent e)
ACTIONS It is common to have multiple ways to activate the same command. The user can choose a certain function through a menu, a keystroke, or a button on a toolbar. This is easy to achieve in the AWT event model: link all events to the same listener.
For example, suppose “ blueAction ” is an action listener whose actionPerformed method changes the background color to blue. You can attach the same object as a listener to several event sources: A toolbar button labeled "Blue" A menu item labeled "Blue" A keystroke CTRL+B
The Action interface has the following methods: void actionPerformed(ActionEvent event) void setEnabled(boolean b) boolean isEnabled() void putValue(String key, Object value) Object getValue(String key) void addPropertyChangeListener (PropertyChangeListener listener) void removePropertyChangeListener (PropertyChangeListener listener)
Name Value NAME The name of the action; displayed on buttons and menu items. SMALL_ICON A place to store a small icon; for display in a button, menu item, or toolbar. SHORT_DESCRIPTION A short description of the icon; for display in a tooltip. LONG_DESCRIPTION A long description of the icon; for potential use in online help. No Swing component uses this value. MNEMONIC_KEY A mnemonic abbreviation; for display in menu items ACCELERATOR_KEY A place to store an accelerator keystroke. No Swing component uses this value. ACTION_COMMAND_KEY Historically, used in the now obsolete registerKeyboardAction method . DEFAULT Potentially useful catch-all property. No Swing component uses this value. Predefined Action Table Names
Note that Action is an interface, not a class. Any class implementing this interface must implement the seven methods we just discussed. Fortunately, a friendly soul has provided a class AbstractAction that implements all methods except for actionPerformed. Steps to carry out the same action in response to a button, a menu item, or a keystroke: Implement a class that extends the AbstractAction class. You may be able to use the same class for multiple related actions. Construct an object of the action class. Construct a button or menu item from the action object. The constructor will read the label text and icon from the action object.
MOUSE EVENTS Mouse Events are generated whenever a mouse moves. MouseEvents are generated like KeyEvents – mousePressed(), mouseReleased(), and mouseClicked(). Handled by using three interface: Mouse Listener Interface Mouse Motion Listener Interface MouseWheelListener Interface.
The MouseListener interface defines five methods: void mousePressed ( MouseEvent e) void mouseReleased ( MouseEvent e) void mouseClicked ( MouseEvent e) void mouseEntered ( MouseEvent e) void mouseExited ( MouseEvent e) Called when the mouse cursor enters/exits component’s visible area mouseClicked (MouseEvent) Invoked when the mouse has been clicked on a component. mouseEntered (MouseEvent) Invoked when the mouse enters a component. mouseExited (MouseEvent) Invoked when the mouse exits a component. mousePressed (MouseEvent) Invoked when a mouse button has been pressed on a component. mouseReleased (MouseEvent) Invoked when a mouse button has been released on a component.
The MouseMotionListener interface adds two methods: void mouseMoved ( MouseEvent e) void mouseDragged ( MouseEvent e) These methods are usually used together with MouseListener methods (i.e., a class implements both interfaces). mouseDragged ( MouseEvent ) Invoked when a mouse button is pressed on a component and then dragged. mouseMoved ( MouseEvent ) Invoked when a mouse cursor has been moved onto a component but no buttons has been pressesd .
The MouseWheelListener interface: The listener interface for receiving mouse wheel events. Has only one method mouseWheelMoved ( MouseEvent ) Invoked when mouse wheel is rotated .
AWT EVENT HIERARCHY Event handling in Java is object oriented, with all events descending from the EventObject class in the java.awt.event package. The EventObject class has a subclass AWTEvent, which is the parent of all AWT event classes
INTRODUCTION TO SWING Swing Features Pluggable look-and feels Lightweight components Do not depend on native peers to render themselves. Simplified graphics to paint on screen Similar behaviour across all platforms Portable look and feel Only a few top level containers not lightweight. New components -- tress tables, sliders progress bars, frames, text components. Tooltips -- textual popup to give additional help Arbitrary keyboard event binding Debugging support
Design Patterns When solving a problem, its not possible to figure out a solution from first principles. Likely to be guided by past experience, or may ask other experts for advice on what has worked for them. Design patterns are a method for presenting this expertise in a structured way.
Various patterns: The MVC pattern swing components. Composite pattern containers and components Decorators scroll pane Strategy pattern Layout managers
Model-View-Controller design pattern Swing uses the model-view-controller architecture (MVC) as the fundamental design behind each of its components. Essentially, MVC breaks GUI components into three elements. Model - (which stores content) View - (to display content on screen) Controller- (handles user Input) Each of these elements plays a crucial role in how the component behaves.
MVC Interaction In MVC, each of the three elements—the model, the view, and the controller—requires the services of another element to keep itself continually updated.
LAYOUT MANAGERS Layout manager automatically arranges several components within a window. Each container object has a layout manager associated with it. Panel,Applet - Flow Layout Frame - Border Layout Whenever a container is resized, the layout manager is used to position each of the components within it.
General syntax for setting layout to container Void setLayout ( LayouManager obj ) The AWT Layout Managers are FlowLayout BorderLayout GridLayout GridbagLayout CardLayout The Swing Layout Managers Are BoxLayout Overlay layout ScrollpaneLayout ViewportLayout SpringLayout
FlowLayout FlowLayout arranges the components in rows from left-to-right and top-to-bottom order based on the order in which they were added to the container. FlowLayout() - create default layout, which centers component and leaves 5 pixels spaces between each component. FlowLayout(int align,int hgap, int vgap)-specify how each line is aligned.
import java.awt.*; public class D extends Frame { public static void main(String arg[]){ Frame f=new Frame(); FlowLayout flow= new FlowLayout(); Button b=new Button(“one”); Button b1=new Button(“two”); Button b2=new Button(“three"); f.setSize(200,200); f.setLayout(flow); f.add(b); f.add(b1); f.add(b2); f.setVisible(true); }}
GridLayout The GridLayout layout manager divides the available space into a grid of cells, evenly allocating the space among all the cells in the grid and placing one component in each cell. Cells are always same size. When you resize the window, the cells grow and shrink, but all the cells have identical sizes.
GridLayout ( int rows, int cols)- construct a grid with specified rows and cols. GridLayout ( int rows, int cols, int hspace , int vspace ) - to specify the amount of horizontal and vertical space that should appear between adjacent components.
import java.awt.*; import javax.swing.*; public class D extends Frame { public static void main(String arg[]){ JFrame f=new JFrame(); GridLayout grid=new GridLayout(2,2); Button b=new Button("one"); Button b1=new Button("two"); Button b2=new Button("three"); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setSize(200,200); f.setLayout(grid); f.add(b); f.add(b1); f.add(b2); f.setVisible(true); }}
BorderLayout BorderLayout divides the container into five areas, and you can add a component to each area. Each of the five areas is associated with a constant value defined in BorderLayout: NORTH, SOUTH, EAST, WEST, and CENTER for the top, bottom, right, left, and center regions, respectively.
BorderLayout() BorderLayout(int hspace, int vspace) – leave space between components. add(b1,BorderLayout.NORTH); add(b2,BorderLayout.SOUTH); add(b3,BorderLayout.CENTER); add(b4,BorderLayout.EAST); add(b5,BorderLayout.WEST);
import java.awt.*; import javax.swing.*; public class D extends Frame { public static void main(String arg[]){ JFrame f=new JFrame(); BorderLayout grid=new BorderLayout(); Button b3=new Button("one"); Button b1=new Button("two"); Button b2=new Button("three"); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setSize(200,200); f.setLayout(grid); f.add(b1,BorderLayout.NORTH); f.add(b2,BorderLayout.SOUTH); f.add(b3,BorderLayout.CENTER); f.setVisible(true); } }
GridBag Layout Gridlayout without limitations In Grid bag layout, the rows and columns have variable sizes. It is possible to merge two adjacent cells and make a space for placing larger components.
Create an object of type GridBagLayout . No need to specify rows and column. GridBagLayout lay =new GridBagLayout () 2. Set this GridBagLayout object to the container. Jpanel p=new Jpanel (); p.setLayout (new GridBagLayout ()); 3. Create an object of type GridBagConstraints . This object will specify how the components are laid out within the grid bag. GridBagConstraints cons=new GridBagConstraints (); 4. For each components, fill in the GridBagConstraints object.Finally add the component with the constraint by using the call add(Component, cons);
GridBagConstraints : Gridx – specify the column position of the component to be added Gridy - specify the row position of the component to be added Gridwidth - specify how many columns occupied by the component Gridheight - specify how many rows occupied by the component
import java.awt.*; import javax.swing.*; public class D extends Frame { public static void main(String arg[]){ JFrame f=new JFrame(); GridBagLayout gb=new GridBagLayout(); GridBagConstraints gc1= new GridBagConstraints(); GridBagConstraints gc2= new GridBagConstraints(); GridBagConstraints gc3= new GridBagConstraints(); Button b3=new Button("one"); Button b1=new Button("two"); Button b2=new Button("three"); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setSize(200,200);
BoxLayout Arrange components in single row or single column. Components are arranged either vertically from top to bottom or horizontally from left to right BoxLayout(Container Obj, BoxLayout.X_AXIS | Y_AXIS);
CardLayout Stacks components on top of each other, displaying the top one Panel cardPanel; CardLayout layout new CardLayout(); cardPanel.setLayout( layout ); ... cardPanel.add( "Card 1" , component1); cardPanel.add( "Card 2" , component2); ... layout.show(cardPanel, "Card 1"); layout.first(cardPanel); layout.next(cardPanel);
OverlayLayout Is a Swing layout manager that arranges components on top of each other.
A SpringLayout lays out the components according to a set of constraints. Each constraint controls the vertical or horizontal distance between two component edges.