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
Slide 1 of 78
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46
Slide 47
47
Slide 48
48
Slide 49
49
Slide 50
50
Slide 51
51
Slide 52
52
Slide 53
53
Slide 54
54
Slide 55
55
Slide 56
56
Slide 57
57
Slide 58
58
Slide 59
59
Slide 60
60
Slide 61
61
Slide 62
62
Slide 63
63
Slide 64
64
Slide 65
65
Slide 66
66
Slide 67
67
Slide 68
68
Slide 69
69
Slide 70
70
Slide 71
71
Slide 72
72
Slide 73
73
Slide 74
74
Slide 75
75
Slide 76
76
Slide 77
77
Slide 78
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


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); } }

Test.html <html> <body> <applet code=”GraphicsDemo4.class” width=”300” height=”300”> </applet> </body> </html>

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 .

Mouse Listener package Listener; import java.awt.Frame ; import java.awt.Label ; import java.awt.TextArea ; import java.awt.event.MouseEvent ; import java.awt.event.MouseListener ; public class Mouse implements MouseListener { TextArea s; public Mouse() { Frame d=new Frame(" kkkk "); s=new TextArea (""); d.add (s); s.addMouseListener (this); d.setSize (190, 190); d.show (); } public void mousePressed ( MouseEvent e) { System.out.println (" MousePressed "); int a= e.getX (); int b= e.getY (); System.out.println ("X="+a+"Y="+b); } public void mouseReleased ( MouseEvent e) { System.out.println (" MouseReleased "); } public void mouseEntered ( MouseEvent e) { System.out.println (" MouseEntered "); } public void mouseExited ( MouseEvent e) { System.out.println (" MouseExited "); } public void mouseClicked ( MouseEvent e) { System.out.println (" MouseClicked "); } public static void main(String arg []) { Mouse a=new Mouse(); }}

Mouse Motion Listener package Listener; import java.awt.event.MouseEvent ; import java.awt.event.MouseMotionListener ; import javax.swing.JFrame ; import javax.swing.JPanel ; import javax.swing.JTextArea ; public class MouseMotionEventDemo extends JPanel implements MouseMotionListener { MouseMotionEventDemo () { JTextArea a=new JTextArea (); a.addMouseMotionListener (this); JFrame b=new JFrame (); b.add (a); b.setVisible (true); } public void mouseMoved ( MouseEvent e) { System.out.println ("Mouse is Moving"); } public void mouseDragged ( MouseEvent e) { System.out.println (" MouseDragged "); } public static void main(String arg []) { MouseMotionEventDemo a=new MouseMotionEventDemo (); }}

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)

Java MouseAdapter Example import java.awt.*; import java.awt.event .*; public class MouseAdapterExample extends MouseAdapter { Frame f; MouseAdapterExample (){ f=new Frame("Mouse Adapter"); f.addMouseListener (this); f.setSize (300,300); f.setLayout (null); f.setVisible (true); } public void mouseClicked ( MouseEvent e) { Graphics g= f.getGraphics (); g.setColor ( Color.BLUE ); g.fillOval ( e.getX (), e.getY (),30,30); } public static void main(String[] args ) { new MouseAdapterExample (); } }

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

Swing component hierarchy: java.lang.Object +-- java.awt.Component +--java.awt.Container | +-- javax.swing.JComponent | +--javax.swing. JButton | +--javax.swing. JLabel | +--javax.swing.JMenuBar | +--javax.swing. JOptionPane | +--javax.swing. JPanel | +--javax.swing. JTextArea | +--javax.swing. JTextField | +--java.awt.Window +--java.awt.Frame +--javax.swing. JFrame

Swing components:

import java.awt.*; import javax.swing.*; public class D extends Frame { public static void main(String arg[]){ JFrame f=new JFrame(); FlowLayout flow= new FlowLayout(); Button b3=new Button("one"); Button b1=new Button("two"); Button b2=new Button("three"); JLabel l=new JLabel("City");

Choice c=new Choice(); c.add("Cheennai"); c.add("Bombay"); c.add("Calcutta"); c.add("Banglore"); JLabel lb1=new JLabel("Name"); JLabel lb2=new JLabel("No"); JLabel lb3=new JLabel("Message"); JTextField t1=new JTextField(20); JTextField t2=new JTextField(15); JTextArea ta=new JTextArea(2,10); Label l11=new Label("Gender"); Label l21=new Label("Languages Known");

CheckboxGroup cg=new CheckboxGroup(); Checkbox c1=new Checkbox("Male",cg,true); Checkbox c2=new Checkbox("Female",cg,false); Checkbox c3=new Checkbox("VisualBasic"); Checkbox c4=new Checkbox("C++"); Checkbox c5=new Checkbox("Java"); Checkbox c6=new Checkbox("C"); List l10=new List(2); l10.add("CSE");l10.add("ECE"); l10.add("EEE");l10.add("MECH"); List l2=new List(3,true); l2.add("CSE");l2.add("ECE");l2.add("EEE");l2.add("MECH"); List l3=new List(4,true);

l3.add("CSE");l3.add("ECE");l3.add("EEE");l3.add("MECH"); JLabel lb11 = new JLabel("Dept"); JLabel lb21 = new JLabel("Dept"); JLabel lb31 = new JLabel("Dept"); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setSize(250,500); f.setLayout(flow); f.add(lb1);f.add(t1); f.add(lb2);f.add(t2); f.add(lb3);f.add(ta); f.add(b1); f.add(b2); f.add(b3);

f.add(l);f.add(c);f.add(l11); f.add(c1); f.add(c2); f.add(l2); f.add(c3); f.add(c4); f.add(c5); f.add(c6); f.add(lb11);f.add(l10);f.add(lb21); f.add(l2);f.add(lb31);f.add(l3); f.setVisible(true); } }

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);

f.setLayout ( gb ); gc1.gridx=0; gc1.gridy=0; gc1.gridwidth=1; gc1.gridheight=1; gc2.gridx=0; gc2.gridy=1; gc2.gridwidth=1; gc2.gridheight=1; gc3.gridx=1;gc3.gridy=1; gc3.gridwidth=1;gc3.gridheight=1; f.add (b1,gc1); f.add (b2,gc2); f.add (b3,gc3); f.setVisible (true); }}

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.
Tags