gui programming, building applets and introduction to annotations:

67
GUI Programming, Building Applets and Introduction to Annotations: Unit-5 By: Vishal Rajput Narmada College of Computer Application-523 Mr. Vishal Rajput

Upload: miyoko

Post on 10-Jan-2016

32 views

Category:

Documents


0 download

DESCRIPTION

GUI Programming, Building Applets and Introduction to Annotations: . Unit-5 By: Vishal Rajput Narmada College of Computer Application-523. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: GUI Programming, Building Applets and Introduction to Annotations:

Mr. Vishal Rajput

GUI Programming, Building Applets and Introduction to Annotations:

Unit-5By: Vishal Rajput

Narmada College of Computer Application-523

Page 2: GUI Programming, Building Applets and Introduction to Annotations:

Mr. Vishal Rajput

• An applet is a special kind of java program that is designed to be transmitted over the internet and automatically executed by a java-compatible web browser.

• Furthermore, an applet is downloaded on demand, just like an image, sound file, or video clip.

• The important difference is that an applet is an intelligent program, not just an animation or media file.

• The Applet class is contained in the java.applet package. Applet contains several methods that give you detailed control over the execution of your applet.

• Java.applet also defines 3 interfaces: AppletContext, AudioClip and AppletStub.• All applets are subclasses of Applet. Thus, all applets must import java.applet.

Applet must also import java.awt (abstract window toolkit). Since all applets run in a window, it is necessary to include support for that window.

Page 3: GUI Programming, Building Applets and Introduction to Annotations:

Mr. Vishal Rajput

• Applets are not executed by the console based java run-time interpreter. Rather they are executed by either a web browser or an applet viewer called appletviewer, provided by the JDK.

• Once an applet has been compiled, it is included in an HTML file using APPLET tag. The applet will be executed by a java-enabled web-browser when it encounters the APPLET tag within the HTML file.

• This requires that the applet code imports the java.awt package that contains the Graphics class. All output operations of an applet are performed using the methods defined in the Graphics class.

• A main() method is not invoked on an applet, and an applet class will not define main().

Page 4: GUI Programming, Building Applets and Introduction to Annotations:

Mr. Vishal Rajput

Demo Program import java.applet.Applet;import java.awt.Graphics;/*<applet code="FirstApplet" width=200 height=200></applet>*/public class FirstApplet extends Applet{public void paint(Graphics g){g.drawString("This is my first applet.",20,100);}}

Page 5: GUI Programming, Building Applets and Introduction to Annotations:

Mr. Vishal Rajput

<html><body><applet code="SecondApplet.java" width=200

height=200></applet></body></html>

Page 6: GUI Programming, Building Applets and Introduction to Annotations:

Mr. Vishal Rajput

• Javac FirstApplet.java• Appletviewer FirstApplet.java• The 1st and 2nd lines import the java.applet.Applet and java.awt.Graphics

classes.• Applet class is the superclass of all applets. The Graphics class is provided by the

awt.• The next lines define a java comment. That comment is HTML source code. The

applet tag specifies which class contains the code for this applet.• It also defines the width and height in pixels of the display area. Applet viewer

reads the HTML and interprets the info that is contained between the applet tags.

• The HTML is not part of the applet and is not used by a web browser. It is used only by the applet viewer.

• The next line declares that firstApplet extends Applet. Each applet that you create must extends this class.

Page 7: GUI Programming, Building Applets and Introduction to Annotations:

Mr. Vishal Rajput

• Paint() is responsible for generating the output of the applet. It accepts a Graphics object as its one argument. It is automatically invoked whenever the applet needs to be displayed.

• The actual output of the string is done by calling the drawString() method of the Graphics object. x,y coordinate – at which to begin the string.

• Applet viewer executes an applet by using the HTML source code. Width and height attributes of the applet tag define the dimensions of the applet display area.

• Applet may also be executed by a web browser.

Page 8: GUI Programming, Building Applets and Introduction to Annotations:

Mr. Vishal Rajput

Applet Life Cycle

Born and initialization state• Applet enters the initialization state when it is first loaded. This is achieved by

calling the init() method of Applet class. The applet is born. At this stage we may do the following if required:

1. Create objects needed by the applet2. Set up initial values3. Load images or fonts4. Set up colors

The initialization occurs only once in the applet’s life cycle. To provide any of the behaviors mentioned above, we must override the init() method.

public void init(){

Action}

Page 9: GUI Programming, Building Applets and Introduction to Annotations:

Mr. Vishal Rajput

Running state(Start)

• Applet enters the running state when the system calls the start() method of Applet class.

• This occurs automatically after the applet is initialized.• Starting can also occur if the applet is already in “stopped” (idle) state. For example, we may leave the web page containing the applet

temporarily to another page and return back to the page. This again starts the applet running. Unlike init() method, the start() method may be called more than once. We may override the start() method to create a thread to control the applet.public void start(){Action}

Page 10: GUI Programming, Building Applets and Introduction to Annotations:

Mr. Vishal Rajput

Idle or Stopped state• An applet becomes idle when it is stopped from running stopping

occurs automatically when we leave the page containing the currently running applet. We can also do so by calling the stop() method explicitly. If we use a thread to run the applet, then we must use stop() method to terminate the thread. We can achieve by overriding the stop() method.

public void stop(){Action}When the browser moves to another page. You can use thismethod to stop additional execution threads

Page 11: GUI Programming, Building Applets and Introduction to Annotations:

Mr. Vishal Rajput

Dead state(destroy)

• An applet is said to be dead when it is removed from memory. This occurs automatically by invoking the destroy() method when we quit the browser. Like initialization, destroying stage occurs only once in the applet’s life cycle. If the applet has created any resources, like threads, we may override the destroy() method to clean up these resources.

public void destroy(){Action}

Page 12: GUI Programming, Building Applets and Introduction to Annotations:

Mr. Vishal Rajput

Display state• Applet moves to the display state whenever it has to perform some

output operations on the screen. This happens immediately after the applet enters into the running state. The paint() method is called to accomplish this task. Almost every applet will have a paint() method.

public void paint( Graphics g) { Display statement; }• It is to be noted that the display state is not considered as a part of

the applet’s life cycle. In fact, the paint() method is defined in the Applet class. It is inherited form the component class, a super class of Applet.

Page 13: GUI Programming, Building Applets and Introduction to Annotations:

Mr. Vishal Rajput

Graphics Class

• A Graphics object encapsulates a set of methods that can perform graphics output.

• Specifically, it allows you to draw lines, ovals, rectangles, strings, images, characters, and arcs.

Page 14: GUI Programming, Building Applets and Introduction to Annotations:

Mr. Vishal Rajput

//Demo program of Graphics classimport java.applet.*;import java.awt.*;/*<applet code="b.class" height="250" width="400"></applet>*/public class b extends Applet{

public void paint(Graphics g){

g.setColor(Color.red);g.drawLine(5,30,350,30);g.setColor(Color.blue);g.drawRect(5,40,90,55);g.fillRect(100,40,90,55);g.setColor(Color.cyan);g.fillRoundRect(195,40,90,55,50,50);g.drawRoundRect(290,40,90,55,20,20);g.setColor(Color.yellow);g.draw3DRect(5,100,90,55,true);g.fill3DRect(100,100,90,55,false);g.setColor(Color.magenta);g.drawOval(195,100,90,55);g.fillOval(290,100,90,55);

}}

Page 15: GUI Programming, Building Applets and Introduction to Annotations:

Mr. Vishal Rajput

AWT v/s Swing ComponentAWT SWING

AWT stands for Abstract windows toolkit. Swing is also called as JFC’s (Java Foundation classes).

AWT components are called Heavyweight component.

Swings are called light weight component because swing components occupies a less memory

AWT components require java.awt package.

Swing components require javax.swing package.

AWT components are platform dependent.

Swing components are made in purely java and they are platform independent.

AWT s not supported look feel . We can have different look and feel in Swing.

Import Java.awt.*; Import javax.swing.*;

Page 16: GUI Programming, Building Applets and Introduction to Annotations:

Mr. Vishal Rajput

Event Handling

• Delegation Event Model– The modern approach to handling events is based

on the delegation event model, which defines standard and consistent mechanisms to generate and process events.

– The delegation event model provides a standard mechanism for a source to generate an event and send it to a set of listeners.

Page 17: GUI Programming, Building Applets and Introduction to Annotations:

Mr. Vishal Rajput

Event• An event is an object that describes a state change in a source. It

can be generated as a consequence of a person interacting with the elements in a graphical user interface.

• Some of the activities that causes events to be generated are pressing a button, entering a character via the keyboard, selecting an item in a list and clicking the mouse.

• Events may also occur that are not directly interact with a user interface. For example, an event may be generated when a timer expires, a counter exceeds a value, a software or hardware failure occurs, or an operation is completed. We are free to define events that are appropriate for our application.

Page 18: GUI Programming, Building Applets and Introduction to Annotations:

Mr. Vishal Rajput

Event Sources

• A source is an object that generates an event. This occurs when the internal state of that object changes in some way. Sources may generate more than one type of event.

• A source must register listeners in order for the listeners to receive notifications about a specific type of event. Each type of event has its own registration method.

Page 19: GUI Programming, Building Applets and Introduction to Annotations:

Mr. Vishal Rajput

Event Listner

• A listener is an object that is notified when an event occurs. It has two major requirements. First, it must have been registered with one or more sources to receive notifications about specific types of events. Second, it must implement methods to receive and process these notifications.

• The method that receive and process events are defined in a set of interfaces found in java.awt.event. For example, the MouseMotionListener interface defines two methods to receive notifications when the mouse is dragged or moved. Any object may receive and process one or both of these events if it provides an implementation of this interface.

Page 20: GUI Programming, Building Applets and Introduction to Annotations:

Mr. Vishal Rajput

Event Object

• At the root of the Java event class hierarchy is EventObject, which is in java.util. it is the superclass for all events. Its one constructor is shown here:– EventObject(Object src)– here, src is the object that generates this event.– EventObject contains two methods:• getSource()• toString()

• The getSource() method returns the source of the event. Its general form is shown here:– Object.getSource()

• toString() returns the string equivalent of the event.

Page 21: GUI Programming, Building Applets and Introduction to Annotations:

Mr. Vishal Rajput

Page 22: GUI Programming, Building Applets and Introduction to Annotations:

Mr. Vishal Rajput

Page 23: GUI Programming, Building Applets and Introduction to Annotations:

Mr. Vishal Rajput

ActionListener

• This interface defines the actionPerformed( ) method that is invoked when an action event occurs. Its general form is shown here:– void actionPerformed(ActionEvent ae)

Page 24: GUI Programming, Building Applets and Introduction to Annotations:

Mr. Vishal Rajput

import java.awt.event.*;import java.awt.*;import java.applet.Applet;

/* <applet code=appl4.class height=200 width=300> </applet> */

public class appl4 extends Applet implements ActionListener{

Label l1,l2;Button b1;TextField t1,t2,r;Panel p1,p2;

public void init(){

l1=new Label("Enter the Number");l2=new Label("Result");t1=new TextField(5);t2=new TextField(5);r=new TextField(5);b1=new Button("Submit");p1=new Panel();p2=new Panel();b1.addActionListener(this);p1.setBackground(Color.pink);p2.setBackground(Color.green);add(p1);add(p2);

p1.add(l1);p1.add(t1);p1.add(t2);p2.add(l2);p2.add(r);p2.add(b1);

}public void actionPerformed(ActionEvent ae){

int n1,n2;n1=Integer.parseInt(t1.getText());n2=Integer.parseInt(t2.getText());r.setText(""+(n1+n2));

}}

Page 25: GUI Programming, Building Applets and Introduction to Annotations:

Mr. Vishal Rajput

Page 26: GUI Programming, Building Applets and Introduction to Annotations:

Mr. Vishal Rajput

The KeyListener Interface

• This interface defines three methods. The keyPressed( ) and keyReleased( ) methods are invoked when a key is pressed and released, respectively. The keyTyped( ) method is invoked when a character has been entered.

• For example, if a user presses and releases the A key, three events are generated in sequence:

key pressed, typed, and released. If a user presses and releases the HOME key, two key events are generated in sequence: key pressed and released.

Page 27: GUI Programming, Building Applets and Introduction to Annotations:

Mr. Vishal Rajput

MouseListener Interface• This interface defines five methods. If the mouse is

pressed and released at the same point, mouseClicked( ) is invoked. When the mouse enters a component, the mouseEntered( ) method is called. When it leaves, mouseExited( ) is called. The mousePressed( ) and mouseReleased( ) methods are invoked when the mouse is pressed and released, respectively.

• The general forms of these methods are shown here:– void mouseClicked(MouseEvent me)– void mouseEntered(MouseEvent me)– void mouseExited(MouseEvent me)– void mousePressed(MouseEvent me)– void mouseReleased(MouseEvent me)

Page 28: GUI Programming, Building Applets and Introduction to Annotations:

Mr. Vishal Rajput

MouseMotionListener Interface

• This interface defines two methods. The mouseDragged( ) method is called multiple times as the mouse is dragged. The mouseMoved( ) method is called multiple times as the mouse is moved. Their general forms are shown here:– void mouseDragged(MouseEvent me)– void mouseMoved(MouseEvent me)

Page 29: GUI Programming, Building Applets and Introduction to Annotations:

Mr. Vishal Rajput

ItemListener Interface

• This interface defines the itemStateChanged( ) method that is invoked when the state of an item changes. Its general form is shown here:– void itemStateChanged(ItemEvent ie)– Eg: CheckBox

Page 30: GUI Programming, Building Applets and Introduction to Annotations:

Mr. Vishal Rajput

WindowListener Interface• This interface defines seven methods. The windowActivated( ) and windowDeactivated( )

methods are invoked when a window is activated or deactivated, respectively. If a window is iconified, the windowIconified( ) method is called. When a window is deiconified, the windowDeiconified( ) method is called. When a window is opened or closed, the windowOpened( ) or windowClosed( ) methods are called, respectively. The windowClosing( ) method is called when a window is being closed.

• The general forms of these methods are– voidwindowActivated(WindowEvent e)Invoked when the Window is set to be the active

Window.– voidwindowClosed(WindowEvent e)Invoked when a window has been closed as the

result of calling dispose on the window.– voidwindowClosing(WindowEvent e)Invoked when the user attempts to close the

window from the window's system menu.– voidwindowDeactivated(WindowEvent e)Invoked when a Window is no longer the

active Window.– voidwindowDeiconified(WindowEvent e)Invoked when a window is changed from a

minimized to a normal state.– voidwindowIconified(WindowEvent e)Invoked when a window is changed from a

normal to a minimized state.– voidwindowOpened(WindowEvent e)Invoked the first time a window is made visible.

Page 31: GUI Programming, Building Applets and Introduction to Annotations:

Mr. Vishal Rajput

Focus Listeners

• Focus listeners listen for a component gaining or losing keyboard focus. Usually there are visual clues as to which component has the focus, such as an active cursor in a text field. The FocusListener interface has two methods, whose signatures are: – public void focusGained(FocusEvent e) – public void focusLost(FocusEvent e)

Page 32: GUI Programming, Building Applets and Introduction to Annotations:

Mr. Vishal Rajput

Adapter Class• If you implement Listener interface then obviously you must have to override all

the methods declare in an interface.

• Suppose in special case you want to just need one or two method among given set of methods then what? If you are implementing listener interface then you can not omit any method.

• Adapter class implements listener interface and contains empty implementation of each method declared in the listener interface, when you extends these Adapter class you need to implement only those methods that you want.

• When we are dealing with Listener interface we are implementing listeners while we working with adapter class we have to extends adapter class and override methods which we need.

Page 33: GUI Programming, Building Applets and Introduction to Annotations:

Mr. Vishal Rajput

List of Adapter class and its Listener Interface:

ComponentAdapter - ComponentAdapterContainerAdapter - ContainerListenerFocusAdapter - FocusListenerKeyAdapter - KeyListenerMouseAdapter - MouseListenerMouseMotionAdapter - MouseMotionListenerWindowAdapter - WindowListener

Page 34: GUI Programming, Building Applets and Introduction to Annotations:

Mr. Vishal Rajput

import java.awt.*;import java.awt.event.*;import java.applet.*;

/* <applet code="AdapterDemo" width=300 height=100></applet>*/

public class AdapterDemo extends Applet{

public void init() {addMouseListener(new MyMouseAdapter(this));addMouseMotionListener(new MyMouseMotionAdapter(this));}

}

class MyMouseAdapter extends MouseAdapter //extends the MouseAdapter class instead of Interface {

AdapterDemo adapterDemo;//Create object of main class to recive the value.public MyMouseAdapter(AdapterDemo adapterDemo) {this.adapterDemo = adapterDemo;// constructor Initialize the value to the main class obj}

// Handle mouse clicked.public void mouseClicked(MouseEvent me) {adapterDemo.showStatus("Mouse clicked");}

}

class MyMouseMotionAdapter extends MouseMotionAdapter {

AdapterDemo adapterDemo;public MyMouseMotionAdapter(AdapterDemo adapterDemo) {this.adapterDemo = adapterDemo;}// Handle mouse dragged.public void mouseDragged(MouseEvent me) {adapterDemo.showStatus("Mouse dragged");}

}

Page 35: GUI Programming, Building Applets and Introduction to Annotations:

Mr. Vishal Rajput

Introduction to layouts

• components are placed on a form is controlled by a "layout manager" that decides how the components lie based on the order that you add( ) them.

• The size, shape, and placement of components will be remarkably different from one layout manager to another. In addition, the layout managers adapt to the dimensions of your applet or application window, so if that window dimension is changed (for example, in the HTML page’s applet specification) the size, shape, and placement of the components could change.

• This section gives you an overview of some layout managers that the Java platform provides, gives you some general rules for using layout managers.

Page 36: GUI Programming, Building Applets and Introduction to Annotations:

Mr. Vishal Rajput

• Some layouts provided by JAVA– Flow Layout (Default Layout) – Border Layout – Grid Layout – Card Layout

Page 37: GUI Programming, Building Applets and Introduction to Annotations:

Mr. Vishal Rajput

Using Flow Layout

• Default layout scheme: the FlowLayout. This simply "flows" the components onto the form, from left to right until the top space is full, then moves down a row and continues flowing the components.

Page 38: GUI Programming, Building Applets and Introduction to Annotations:

Mr. Vishal Rajput

import java.awt.*;import java.awt.event.*;import java.applet.*;public class flowlayout extends Applet implements ItemListener {String msg=" ";Checkbox Win98,winNT,solaris,mac;public void init(){

setLayout(new FlowLayout(FlowLayout.LEFT));Win98=new Checkbox("Windows 98",null,true);winNT=new Checkbox("Windows NT");solaris=new Checkbox("MacOS");

add(Win98);add(winNT);add(solaris);add(mac);Win98.addItemListener(this);winNT.addItemListener(this);solaris.addItemListener(this);mac.addItemListener(this);

}public void itemStateChanged(ItemEvent id) {repaint();}

public void paint(Graphics g) {msg="Current state : ";g.drawString(msg,6,80);msg="Windows 98 : " + Win98.getState();g.drawString(msg,6,100);msg="Windows NT : " + winNT.getState();g.drawString(msg,6,120);msg="Solaris : " + solaris.getState();g.drawString(msg,6,140);msg="Mac : " + mac.getState();g.drawString(msg,6,160);}

}

Page 39: GUI Programming, Building Applets and Introduction to Annotations:

Mr. Vishal Rajput

Using Border Layout

• This layout manager has the concept of four border regions and a center area. When you add something to a panel that’s using a BorderLayout you must use an add( ) method that takes a String object as its first argument, and that string must specify (with proper capitalization) "North" (top), "South" (bottom), "East" (right), "West" (left), or "Center." If you misspell or miss-capitalize, you won’t get a compile-time error, but the applet simply won’t do what you expect.

Page 40: GUI Programming, Building Applets and Introduction to Annotations:

Mr. Vishal Rajput

import java.applet.Applet;import java.awt.*;import java.awt.event.*;

public class border extends Applet{

Scrollbar hscr1,hscr2,vscr1,vscr2;TextField txtbox;public void init(){setLayout(new BorderLayout());hscr1 = new Scrollbar(Scrollbar.HORIZONTAL,1,10,1,200);hscr2 = new Scrollbar(Scrollbar.HORIZONTAL,1,10,1,200);vscr1 = new Scrollbar(Scrollbar.VERTICAL,1,10,1,200);vscr2 = new Scrollbar(Scrollbar.VERTICAL,1,10,1,200);txtbox = new TextField("Welcome to Border Layout");add("North",hscr1);add("West",vscr1);add("South",hscr2);add("East",vscr2);add("Center",txtbox);}

}

Page 41: GUI Programming, Building Applets and Introduction to Annotations:

Mr. Vishal Rajput

GridLayout

• A GridLayout allows you to build a table of components, and as you add them they are placed left-to-right and top-to-bottom in the grid. In the constructor you specify the number of rows and columns that you need and these are laid out in equal size.

Page 42: GUI Programming, Building Applets and Introduction to Annotations:

Mr. Vishal Rajput

import java.awt.*;import java.applet.*;public class gridlayout extends Applet {static final int n=4;public void init() {setLayout(new GridLayout(n,n));setFont(new Font("SansSerif",Font.BOLD,24));for(int i=0;i<n;i++){for(int j=0;j<n;j++){int k=i*n+j;if(k>0)add(new Button(" " +k));}}}}

Page 43: GUI Programming, Building Applets and Introduction to Annotations:

Mr. Vishal Rajput

Using Card Layout

• The CardLayout allows you to create the rough equivalent of a "tabbed dialog," which in more sophisticated environments has actual file-folder tabs running across one edge, and all you have to do is press a tab to bring forward a different dialog. Not so in the AWT: The CardLayout is simply a blank space and you’re responsible for bringing forward new cards

Page 44: GUI Programming, Building Applets and Introduction to Annotations:

Mr. Vishal Rajput

import java.awt.*;import java.awt.event.*;import java.applet.*;public class cardlayout extends Applet implements ActionListener, MouseListener {Checkbox Win98,winNT,solaris,mac;Panel oscards;CardLayout cardlo;Button win,other;public void init(){win=new Button("Windows");other=new Button("Other");add(win);add(other);cardlo=new CardLayout();oscards=new Panel();oscards.setLayout(cardlo);Win98=new Checkbox("Windows 98",null,true);winNT=new Checkbox("Windows NT");solaris=new Checkbox("Solaris");mac=new Checkbox("MacOS");Panel winpan=new Panel();winpan.add(Win98);winpan.add(winNT);Panel otherpan=new Panel();otherpan.add(solaris);otherpan.add(mac);oscards.add(winpan,"Windows");oscards.add(otherpan,"Other");add(oscards);win.addActionListener(this);other.addActionListener(this);addMouseListener(this);}public void mousePressed(MouseEvent me) {cardlo.next(oscards);}public void mouseClicked(MouseEvent me) {}public void mouseEntered(MouseEvent me) {}public void mouseExited(MouseEvent me) {}public void mouseReleased(MouseEvent me) {}public void actionPerformed(ActionEvent ae) {if(ae.getSource() == win) {cardlo.show(oscards,"Windows");}else{cardlo.show(oscards,"Other");}}}

Page 45: GUI Programming, Building Applets and Introduction to Annotations:

Mr. Vishal Rajput

PARAM Teg

• The PARAM tag allows you to specify applet-specific arguments in an HTML page. Applets access their attributes with the getParameter( ) method.

• It returns the value of the specified parameter in the form of a String object. Thus, for numeric and boolean values, you will need to convert their string representations into their internal formats.

Page 46: GUI Programming, Building Applets and Introduction to Annotations:

Mr. Vishal Rajput

/* <applet code="MyApplet2.class" width = 600 height= 450><param name = "t1" value="Shree Ganesh"><param name = "t2" value ="1985"></applet> */import java.applet.*;import java.awt.*;public class MyApplet2 extends Applet{ String n;String id;

public void init(){ n = getParameter("t1");id = getParameter("t2");}

public void paint(Graphics g){ g.drawString("Name is : " + n, 100,100);g.drawString("Id is : "+ id, 100,150);}

}

Page 47: GUI Programming, Building Applets and Introduction to Annotations:

Mr. Vishal Rajput

AWT Component Properties

Page 48: GUI Programming, Building Applets and Introduction to Annotations:

Mr. Vishal Rajput

Buttons

• Properties of Button– To create push button: Button b1 =new Button("label");– To get the label of the button: String l = b1.getLabel();– To set the label of the button: b1.setLabel("label");– To get the label of the button clicked: String str =

ae.getActionCommand();

Page 49: GUI Programming, Building Applets and Introduction to Annotations:

Mr. Vishal Rajput

CheckBox

• A Checkbox is a square shaped box which provides a set of options to the user.– To create a Checkbox: Checkbox cb = new Checkbox

("label");– To create a checked Checkbox: Checkbox cb = new

Checkbox ("label", true);– To get the state of a Checkbox: boolean b = cb.getState

();– To set the state of a Checkbox: cb.setState (true);– To get the label of a Checkbox: String s = cb.getLabel ();

Page 50: GUI Programming, Building Applets and Introduction to Annotations:

Mr. Vishal Rajput

Radio button

• A Radio button represents a round shaped button such that only one can be selected from a panel. Radio button can be created using CheckboxGroup class and Checkbox classes.– To create a radio button: CheckboxGroup cbg = new

CheckboxGroup ();– Checkbox cb = new Checkbox ("label", cbg, true);– To know the selected checkbox: Checkbox cb =

cbg.getSelectedCheckbox ();– To know the selected checkbox label: String label =

cbg.getSelectedCheckbox ().getLabel ();

Page 51: GUI Programming, Building Applets and Introduction to Annotations:

Mr. Vishal Rajput

Choice Menu:

• Choice menu is a popdown list of items. Only one item can be selected.– To create a choice menu: Choice ch = new Choice();– To add items to the choice menu: ch.add ("text");– To know the name of the item selected from the choice

menu:• String s = ch.getSelectedItem ();• To know the index of the currently selected item: int i =

ch.getSelectedIndex();– This method returns -1, if nothing is selected.

Page 52: GUI Programming, Building Applets and Introduction to Annotations:

Mr. Vishal Rajput

List box

• A List box is similar to a choice box, it allows the user to select multiple items.– To create a list box: List lst = new List();

(or)

– List lst = new List (3, true);• This list box initially displays 3 items. The next parameter true

represents that the user can select• more than one item from the available items. If it is false, then the

user can select only one item.– To add items to the list box: lst.add("text");– To get the selected items: String x[] = lst.getSelectedItems();– To get the selected indexes: int x[] = lst.getSelectedIndexes ();

Page 53: GUI Programming, Building Applets and Introduction to Annotations:

Mr. Vishal Rajput

• Label: A label is a constant text that is displayed with a text.– To create a label: Label l = new Label("text",alignmentConstant);– Note: - alignmentconstant: Label.RIGHT, Label.LEFT and Label.CENTER

• TextField: TextField allows a user to enter a single line of text.– To create a TextField: TextField tf = new TextField(25);

(or)– TextField tf = new TextField ("defaulttext", 25);– To get the text from a TextField: String s = tf.getText();– To set the text into a TextField: tf.setText("text");– To hide the text being typed into the TextField by a character:

tf.setEchoChar('char');

• TextArea: TextArea is similar to a TextField, but it accepts more than one line of text.– To create a TextArea: TextArea ta = new TextArea();

(or)– TextArea ta = new TextArea (rows, cols);– Note: TextArea supports getText () and setText ()

Page 54: GUI Programming, Building Applets and Introduction to Annotations:

Mr. Vishal Rajput

Scrollbar• Scrollbar class is useful to create scrollbars that can be attached to a

frame or text area. Scrollbars can be arranged vertically or horizontally.– To create a scrollbar : Scrollbar sb = new Scrollbar (alignment, start, step,

min, max);– alignment: Scrollbar.VERTICAL, Scrollbar.HORIZONTAL

• start: starting value (e.g. 0)• step: step value (e.g. 30) // represents scrollbar length• min: minimum value (e.g. 0)• max: maximum value (e.g. 300)

– To know the location of a scrollbar: int n = sb.getValue ();– To update scrollbar position to a new position: sb.setValue (int position);– To get the maximum value of the scrollbar: int x = sb.getMaximum ();– To get the minimum value of the scrollbar: int x = sb.getMinimum ();– To get the alignment of the scrollbar: int x = getOrientation ();

• This method return 0 if the scrollbar is aligned HORIZONTAL, 1 if aligned VERTICAL.

Page 55: GUI Programming, Building Applets and Introduction to Annotations:

Mr. Vishal Rajput

Container

• Panel• Frame

Page 56: GUI Programming, Building Applets and Introduction to Annotations:

Mr. Vishal Rajput

FRAME WINDOW• A window represents a box shaped area on the screen. Window does not have border and

title.

• A Frame is a top level window that is not contained in another window. A Frame contains border and title.

• Frame encapsulates what is commonly thought of as a “window.” It is a subclass of Window and has a title bar, menu bar, borders, and resizing corners. If you create a Frame object from within an applet, it will contain a warning message, such as “Java Applet Window,” to the user that an applet window has been created. This message warns users that the window they see was started by an applet and not by software running on their computer When a Frame window is created by a stand-alone application rather than an applet, a normal window is created.

• Toolkitclass has been used to get the image and then the image is used to display as frame icon. Toolkit class is used to bind the various components to particular native toolkit implementations.

getDefaultToolkit(): //This method returns the default toolkit. getImage(url or filename):

//This method retrieves the pixels data of the image which can be either in format of .gif, .jpegor .png.

Page 57: GUI Programming, Building Applets and Introduction to Annotations:

Mr. Vishal Rajput

Creating the Frame:• We can create a Frame by creating Frame class object.

Frame obj = new Frame ();(or)

• Create a class that extends Frame class then create an object to that class. class MyClass extends Frame MyClass obj = new MyClass ();

• After creating the Frame we need to set Frame width and height using setSize () method as:

f.setSize (400, 350);• We can display the frame using setVisible () method as: f.setVisible (true);

Page 58: GUI Programming, Building Applets and Introduction to Annotations:

Mr. Vishal Rajput

//Write a program to create a Frame without extending Frame class

import java.awt.*;class MyFrame{

public static void main(String args[]){

Frame f1 = new Frame ();f1.setSize (500,150);f1.setTitle ("GUI World");f1.setVisible (true);

}}

Page 59: GUI Programming, Building Applets and Introduction to Annotations:

Mr. Vishal Rajput

//With extending Frame Classimport java.awt.*;class MyFrame extends Frame{

public static void main(String args[]){ MyFrame f1 = new MyFrame ();f1.setSize (500,200);f1.setTitle ("GUI World");f1.setVisible (true);}

}• The frame can be minimized, maximized and resized but cannot be

closed. Even if we click on close button of the frame, it will not perform any closing action. Closing a frame means attaching action to the component. To attach actions to the components, we need ‘Event Delegation Model’.

Page 60: GUI Programming, Building Applets and Introduction to Annotations:

Mr. Vishal Rajput

Menus• We can also develop an application with a Menu.As a name indicates a Menu

consists of Menu objects. These Menu objects comprise of MenuItem objects which can be selected by the user with a click of a mouse. A MenuItem may be a String, checkbox, separator, menu etc.

• Following are the steps to to add menus to any Frame: 1. You need to create a MenuBar first with the help of the following method.

– MenuBar mb = new MenuBar();

2. Then you need to create a Menu using Menu m = new Menu("File");. 3. Now theMenuItem options can be added to the Menu from top to bottom, using

the following methods. mi.add(new MenuItem("Open"));

mi.add(new CheckboxMenuItem("Type here"));

4. Now you can add the Menu to the MenuBar from left to right using mi.add(m);. 5. Finally, you need to add the MenuBar to the Frame by calling the setMenuBar()

method.

Page 61: GUI Programming, Building Applets and Introduction to Annotations:

Mr. Vishal Rajput

import java.awt.*; import java.awt.event.*; public class MainWindow extends Frame { public MainWindow() { super("Menu Window"); setSize(400, 400);

FileMenu fileMenu = new FileMenu(this);

MenuBar mb = new MenuBar(); mb.add(fileMenu);

setMenuBar(mb);

addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) { exit(); } }); } public void exit() { setVisible(false); dispose(); System.exit(0); }

public static void main(String args[]) { MainWindow w = new MainWindow(); w.setVisible(true); } }

Page 62: GUI Programming, Building Applets and Introduction to Annotations:

Mr. Vishal Rajput

class FileMenu extends Menu implements ActionListener { MainWindow mw; public FileMenu(MainWindow m) { super("File");

mw = m; MenuItem mi;

add(mi = new MenuItem("Open")); mi.addActionListener(this); add(mi = new MenuItem("Close")); mi.addActionListener(this); add(mi = new MenuItem("Exit")); mi.addActionListener(this);

} public void actionPerformed(ActionEvent e) { String item = e.getActionCommand();

if (item.equals("Exit")) mw.exit();

else System.out.println("Selected FileMenu " + item);

} }

Page 63: GUI Programming, Building Applets and Introduction to Annotations:

Mr. Vishal Rajput

Collection Framework or Container Class

• In order to handle group of objects we can use array of objects. If we have a class called Employ with members name and id, if we want to store details of 10 Employees, create an array of object to hold 10 Employ details.

• Employ ob [] = new Employ [10];• We cannot store different class objects into same array.• Inserting element at the end of array is easy but at the

middle is difficult.• After retriving the elements from the array, in order to

process the elements we don’t have any methods

Page 64: GUI Programming, Building Applets and Introduction to Annotations:

Mr. Vishal Rajput

Collection Object/Container Class• A collection object is an object which can store group of other objects.

• A collection object has a class called Collection class or Container class.

• All the collection classes are available in the package called 'java.util’ (util stands for utility).

• Group of collection classes is called a Collection Framework.

• A collection object does not store the physical copies of other objects; it stores references of other objects.

• All the collection classes in java.util package are the implementation classes of different interfaces.

Page 65: GUI Programming, Building Applets and Introduction to Annotations:

Mr. Vishal Rajput

Interface of Container Class

Page 66: GUI Programming, Building Applets and Introduction to Annotations:

Mr. Vishal Rajput

• Set: A Set represents a group of elements (objects) arranged just like an array. The set will grow dynamically when the elements are stored into it. A set will not allow duplicate elements.

• List: Lists are like sets but allow duplicate values to be stored.• Queue: A Queue represents arrangement of elements in FIFO

(First In First Out) order. This means that an element that is stored as a first element into the queue will be removed first from the queue.

• Map: Maps store elements in the form of key value pairs. If the key is provided its corresponding value can be obtained.

Page 67: GUI Programming, Building Applets and Introduction to Annotations:

Mr. Vishal Rajput