+ All Categories
Home > Documents > GUI Programming, Building Applets and Introduction to Annotations:

GUI Programming, Building Applets and Introduction to Annotations:

Date post: 06-Jan-2016
Category:
Upload: debbie
View: 40 times
Download: 0 times
Share this document with a friend
Description:
GUI Programming, Building Applets and Introduction to Annotations: . Unit-5 By: Vishal Rajput Narmada College of Computer Application-523. - PowerPoint PPT Presentation
Popular Tags:
107
GUI Programming, Building Applets and Introduction to Annotations: Unit-5 By: Vishal Rajput Narmada College of Computer Application-523 Mr. Vishal Rajput
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.*; class AWTMenu extends Frame { MenuBar mbar; Menu menu,submenu; MenuItem m1,m2,m3,m4,m5; public AWTMenu() { // Set frame properties setTitle("AWT Menu"); // Set the title setSize(400,400); // Set size to the frame setLayout(new FlowLayout()); // Set the layout setVisible(true); // Make the frame visible //setLocationRelativeTo(null); // Center the frame // Create the menu bar mbar=new MenuBar(); // Create the menu menu=new Menu("Menu"); // Create the submenu submenu=new Menu("Sub Menu"); // Create MenuItems m1=new MenuItem("Menu Item 1"); m2=new MenuItem("Menu Item 2"); m3=new MenuItem("Menu Item 3"); m4=new MenuItem("Menu Item 4"); m5=new MenuItem("Menu Item 5"); // Attach menu items to menu menu.add(m1); menu.add(m2); menu.add(m3); // Attach menu items to submenu submenu.add(m4); submenu.add(m5); // Attach submenu to menu menu.add(submenu);

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

Mr. Vishal Rajput

// Attach menu to menu bar mbar.add(menu); // Set menu bar to the frame setMenuBar(mbar); }

public static void main(String args[]) { new AWTMenu(); AWTMenu mo=new AWTMenu();

mo.addWindowListener (new MyClass ()); } } class MyClass extends WindowAdapter{

public void windowClosing (WindowEvent e){

System.exit (0);}

}

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

Mr. Vishal Rajput

Generic Types

• Generic type represents classes, interfaces and methods in a type safe manner.

• Generic types can act on any type of data.• All Generic types are subclasses of Object class, it acts

on Objects only.• Generic types act on advanced data type only.• It is not possible to create an object to Generic type

itself.• Using generic types, we can avoid casting in many

cases.

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

Mr. Vishal Rajput

Generic Class

When we create a class with an instance variable to store an Integer object, it can be used to store Integer type data only. We cannot use that instance variable to store a Float class object or a String type Object. To store different types of data into a class, we have to write the same class again and again by changing the data type of the variables. This can be avoided using a generic class. A generic class represents a class that is type-safe. This means a generic class can act upon any data type.

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

Mr. Vishal Rajput

//Example for Generic Classclass MyClass<T>{ T obj;

MyClass (T obj){

this.obj = obj;}T getObj (){

return obj;}

}class Gen1{

public static void main(String args[]){Integer i1 = new Integer (10);MyClass<Integer> obj1 = new MyClass<Integer>(i1);

System.out.println ("U stored : " + obj1.getObj() );Double d1 = new Double(30.66);MyClass<Double> obj2 = new MyClass<Double>(d1);

System.out.println ("U Stored : " + obj2.getObj() );MyClass<String> obj3 = new MyClass<String>("Suresh Kumar");

System.out.println ("U Stored : " + obj3.getObj() );}

}

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

Mr. Vishal Rajput

Generic Method

We can make a method alone as generic method by writing the generic parameter before the method return type as:<T> returntype methodname (){

Method code;}e.g.: <T> void display_data (){

Method body;}

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

Mr. Vishal Rajput

class MyClass{

<T>void display_data (T arr[]){for (int i=0;i<arr.length; i++)System.out.print ("\t" + arr[i]);System.out.println ();}

}class Gen12{

public static void main(String args[]){ MyClass obj = new MyClass ( );Integer a[] = {1,2,3,4,5,6};System.out.print ("Reading Integer Objects: ");obj.display_data (a);Float b[] = {1.1f,2.2f,3.4f};System.out.print ("Reading Float Objects: ");obj.display_data (b);String c[] = {"Subash","Chandra","Bose"};System.out.print ("Reading String Objects: ");obj.display_data (c);}

}

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

Mr. Vishal Rajput

Generic InterfaceIt is possible to develop an interface using generic type concept. The general form of generic interface looks like:interface interface_name <T>{

//method that accepts any objectreturn_type method_name ( T object_name );

}

Here, T represents any data type which is used in the interface. We can write an implementationclass for the above interface as:

class class_name <T> implements interface_name <T>{

public return_type method_name ( T object_name ){

//provide body of the method}

}

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

Mr. Vishal Rajput

//A generic interfaceinterface inter<T>{

void displayData (T obj);}

class AnyClass<T> implements inter<T>{

public void displayData (T t1){

System.out.println ("Entered value is : " + t1);}

}

class Gen123{

public static void main (String args[]){

AnyClass<Integer> ob1 = new AnyClass<Integer>();ob1.displayData (new Integer (10) );AnyClass<String> ob2 = new AnyClass<String>();ob2.displayData (new String ("Conal Beaty") );

}}

Page 70: 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 retrieving the elements from the array, in order to

process the elements we don’t have any methods

Page 71: 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 72: 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 73: GUI Programming, Building Applets and Introduction to Annotations:

Mr. Vishal Rajput

• Retrieving Elements from Collections: Following are the ways to retrieve any element from a collection object:– Using Iterator interface.– Using ListIterator interface.– Using Enumeration interface.

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

Mr. Vishal Rajput

• Iterator Interface: Iterator is an interface that contains methods to retrieve the elements one by one from a collection object. It retrieves elements only in forward direction. It has 3 methods:

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

Mr. Vishal Rajput

• ListIterator Interface: ListIterator is an interface that contains methods to retrieve the elements from a collection object, both in forward and reverse directions. It can retrieve the elements in forward and backward direction. It has the following important methods:

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

Mr. Vishal Rajput

• Enumeration Interface: This interface is useful to retrieve elements one by one like Iterator. It has 2 methods.

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

Mr. Vishal Rajput

• HashSet Class: HashSet represents a set of elements (objects). It does not guarantee the order of elements. Also it does not allow the duplicate elements to be stored.– We can write the HashSet class as: class HashSet<T>– We can create the object as: HashSet<String> hs = new

HashSet<String> ();• The following constructors are available in HashSet:

– HashSet();– HashSet (int capacity); Here capacity represents how many

elements can be stored into the HashSet initially. This capacity may increase automatically when more number of elements is being stored.

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

Mr. Vishal Rajput

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

Mr. Vishal Rajput

//HashSet Demoimport java.util.*;class HS{

public static void main(String args[]){ //create a HashSet to store StringsHashSet <String> hs = new HashSet<String> ();//Store some String elements

hs.add ("India");hs.add ("America");hs.add ("Japan");hs.add ("China");hs.add ("America");

//view the HashSetSystem.out.println ("HashSet = " + hs);

//add an Iterator to hsIterator it = hs.iterator ();

//display element by element using IteratorSystem.out.println ("Elements Using Iterator: ");

while (it.hasNext() ){

String s = (String) it.next (); System.out.println(s);

} }}

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

Mr. Vishal Rajput

LinkedHashSet Class: This is a subclass of HashSet class. LinkedHashSet internally uses a linked list to store the elements. It is a generic class that has the declaration:class LinkedHashSet<T>

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

Mr. Vishal Rajput

Stack Class

• A stack represents a group of elements stored in LIFO (Last In First Out) order. This means that the element which is stored as a last element into the stack will be the first element to be removed from the stack. Inserting the elements (Objects) into the stack is called push operation and removing the elements from stack is called pop operation. Searching for an element in stack is called peep operation. Insertion and deletion of elements take place only from one side of the stack, called top of the stack. We can write a Stack class as:

• class Stack<E>• e.g.: Stack<Integer> obj = new Stack<Integer> ();

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

Mr. Vishal Rajput

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

Mr. Vishal Rajput

//pushing, popping, searching elements in a stackimport java.util.*;class StackDemo{

public static void main(String args[]){

//create an empty stack to contain Integer objectsStack<Integer> st = new Stack<Integer>();st.push (new Integer(10) );st.push (new Integer(20) );st.push (new Integer(30) );st.push (new Integer(40) );st.push (new Integer(50) );

System.out.println (st);System.out.println ("Element at top of the stack is : " + st.peek() ); System.out.println ("Removing element at the TOP of the stack : " + st.pop());

System.out.println ("The new stack is : " + st); }}

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

Mr. Vishal Rajput

LinkedList Class

• A linked list contains a group of elements in the form of nodes. Each node will have three fields- the data field contatins data and the link fields contain references to previous and next nodes.A linked list is written in the form of:

• class LinkedList<E>• we can create an empty linked list for storing

String type elements (objects) as:LinkedList <String> ll = new LinkedList<String> ();

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

Mr. Vishal Rajput

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

Mr. Vishal Rajput

import java.util.*;//Linked Listclass LinkedDemo{

public static void main(String args[]){ LinkedList <String> ll = new LinkedList<String>();

ll.add ("India");ll.add ("Pakistan");ll.add ("South America");ll.add ("Africa");ll.addFirst ("Europe");ll.add (1,"Australia");ll.add (2,"Antarctica");

System.out.println ("Elements in Linked List is : " + ll);System.out.println ("Size of the Linked List is : " + ll.size() );}}

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

Mr. Vishal Rajput

ArrayList Class

• An ArrayList is like an array, which can grow in memory dynamically. ArrayList is not synchronized. This means that when more than one thread acts simultaneously on the ArrayList object, the results may be incorrect in some cases. ArrayList class can be written as:

• class ArrayList <E>• We can create an object to ArrayList as: ArrayList <String> arl = new ArrayList<String> ();

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

Mr. Vishal Rajput

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

Mr. Vishal Rajput

import java.util.*;//ArrayList Democlass ArrayListDemo{

public static void main(String args[]){

ArrayList <String> al = new ArrayList<String>();al.add ("Asia");al.add ("North America");al.add ("South America");al.add ("Africa");al.add ("Europe");al.add (1,"Australia");al.add (2,"Antarctica");

System.out.print ("Size of the Array List is: " + al.size ());System.out.print ("\nRetrieving elements in ArrayList using Iterator :");

Iterator it = al.iterator ();while (it.hasNext () )System.out.print (it.next () + "\t");}

}

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

Mr. Vishal Rajput

HashMap Class• HashMap is a collection that stores elements in the form of key-value pairs.

If key is provided its corresponding value can be easily retrieved from the HAshMap. Keys should be unique. HashMap is not synchronized and hence while using multiple threads on HashMap object, we get unreliable results.

• We can write HashMap class as: class HashMap<K, V>• For example to store a String as key and an integer object as its value, we can

create the HashMap as: HashMap<String, Integer> hm = new HashMap<String, Integer> ();• The default initial capacity of this HashMap will be taken as 16 and the load

factor as 0.75. Load factor represents at what level the HashMap capacity should be doubled. For example, the product of capacity and load factor = 16 * 0.75 = 12. This represents that after storing 12th keyvalue pair into the HashMap, its capacity will become 32.

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

Mr. Vishal Rajput

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

Mr. Vishal Rajput

import java.util.*;class HashMapDemo{ public static void main(String args[]){

HashMap<Integer, String> hm = new HashMap<Integer, String> ();hm.put (new Integer (101),"Naresh");hm.put (new Integer (102),"Rajesh");hm.put (new Integer (103),"Suresh");hm.put (new Integer (104),"Mahesh");hm.put (new Integer (105),"Ramesh");Set<Integer> set = new HashSet<Integer>();set = hm.keySet();System.out.println (set);

}}

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

Mr. Vishal Rajput

Hashtable Class• Hashtable is a collection that stores elements in the form of key-

value pairs. If key is provided later its corresponding value can be easily retrieved from the HAshtable. Keys should be unique. We can write Hashtable class as: class Hashtable<K,V>

• For example to store a String as key and an integer object as its value, we can create the Hashtable as: Hashtable<String, Integer> ht = new Hashtable<String, Integer> ();

• The default initial capacity of this Hashtable will be taken as 11 and the load factor as 0.75. Load factor represents at what level the Hashtable capacity should be doubled. For example, the product of capacity and load factor = 11 * 0.75 = 8.25. This represents that after storing 8th keyvalue pair into the Hashtable, its capacity will become 22.

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

Mr. Vishal Rajput

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

Mr. Vishal Rajput

//Hashtable Demoimport java.util.*;class HashtableDemo{ public static void main(String args[]){Hashtable<Integer, String> ht = new Hashtable<Integer, String> ();ht.put (new Integer (101),"Naresh");ht.put (new Integer (102),"Rajesh");ht.put (new Integer (103),“Conal");ht.put (new Integer (104),“Rohit");ht.put (new Integer (105),“Nilay");Enumeration e = ht.keys ();while ( e.hasMoreElements () ){Integer i1 = (Integer) e.nextElement ();System.out.println (i1 + "\t" + ht.get (i1));}}}

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

Mr. Vishal Rajput

Swing and MVC

• About Swing Swing components comprises of a large

percentage of the JFC release. The swing component toolkit consists of over 250 pure java classes and 75 interfaces contained in about 10 packages. They are used to build lightweight user interface. Swing consists of user interface(UI) classes and non user interface classes. The non-UI classes provide services and other operations for the UI classes.

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

Mr. Vishal Rajput

Features of Swing Component• MVC Architecture: The user can provide his own data model for a component by sub-

classing the Model class or by implementing the appropriate interface. The Model-View-Controller (MVC) architecture is used continually throughout the swing component set. The view and controller parts of the architecture are combined in the component.-MVC structure is split into three separate sections.

Model - Contains the data for your program, along with the logic, methods and functions to manipulate this data.View - Means of displaying the data within the model. Probably a GUI, but could be audio, printouts or any kind of thing.Controller - Maps the users actions in the view to model updates

• Action Objects: action interface objects provide a single point of control for program actions. An example of this would be a toolbar icon and a menu item referencing the same Action objects. When action object disabled, the GUI items that reference it are automatically disabled.

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

Mr. Vishal Rajput

• Pluggable look and feel: The user can select a look and feel and this can be plugged in. An interface made of Swing components can look like a Win32 app, a Motif app. It can use the new Metal look and feel.

• Wide variety of components: Class names that starts with J are the components that are added to and application. For ex. JButton, JList, JPanel.

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

Mr. Vishal Rajput

JCOMPONENT

• The JComponent class is the root of the visual component class hierarchy in the JFC. The visual components are known as the “J” classes. The functionality contained in the Jcomponent class is available to all the visual components contained in the JFC. The JComponent class is repository of functionality for all visual components. The JComponent class is at the top of the hierarchy of all visual components contained in the JFC. The hierarchy is shown in the following figure.

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

Mr. Vishal Rajput

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

Mr. Vishal Rajput

• Creating a Frame: Create an object to JFrame: JFrame ob = new JFrame ("title"); (or)• Create a class as subclass to JFrame class:

MyFrame extends JFrame Create an object to that class : MyFrame ob = new MyFrame ();

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

Mr. Vishal Rajput

Write a program to create a frame by creating an object to JFrame class.//A swing Frameimport javax.swing.*;class MyFrame{

public static void main (String agrs[]){

JFrame jf = new JFrame ("My Swing Frame...");jf.setSize (400,200);jf.setVisible (true);jf.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);

}}

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

Mr. Vishal Rajput

Note: To close the frame, we can take the help of getDefaultCloseOperation () method ofJFrame class, as shown here: getDefaultCloseOperation (constant);where the constant can be any one of the following:· JFrame.EXIT_ON_CLOSE: This closes the application upon clicking on close button.· JFrame.DISPOSE_ON_CLOSE: This disposes the present frame which is visible on the screen. The JVM may also terminate.· JFrame.DO_NOTHING_ON_CLOSE: This will not perform any operation upon clicking onclose button.· JFrame.HIDE_ON_CLOSE: This hides the frame upon clicking on close button.

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

Window Panes

• Window Panes: In swings the components are attached to the window panes only.A window pane represents a free area of a window where some text or components can be displayed. For example, we can create a frame using JFrame class in javax.swing which contains a free area inside it, this free area is called 'window pane'. Four types of window panes are available in javax.swing package.

Mr. Vishal Rajput

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

Mr. Vishal Rajput

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

Mr. Vishal Rajput

· Glass Pane: This is the first pane and is very close to the monitors screen. Any components to be displayed in the foreground are attached to this glass pane. To reach this glass pane, we use getGlassPane () method of JFrame class.

· Root Pane: This pane is below the glass pane. Any components to be displayed in the background are displayed in this pane. Root pane and glass pane are used in animations also. For example, suppose we want to display a flying aeroplane in the sky. The airplane can be displayed as a .gif or .jpg file in the glass pane where as the blue sky can be displayed in the root pane in the background. To reach this root pane, we use getRootPane () method of JFrame class.

· Layered Pane: This pane lies below the root pane. When we want to take several components as a group, we attach them in the layered pane. We can reach this pane by calling getLayeredPane () method of JFrame class.

· Content Pane: This is the bottom most pane of all. Individual components are attached to this pane. To reach this pane, we can call getContentPane () method of JFrame class.

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

Wrire a program to display text in the frame.import javax.swing.*;import java.awt.*;class MyPanel extends JPanel{ public void paintComponent (Graphics g)

{ super.paintComponent (g); //call JPanel’s methodsetBackground (Color.red);g.setColor (Color.white);g.setFont (new Font("Courier New",Font.BOLD,30));g.drawString ("Hello Readers!", 50, 100);

}}class FrameDemo extends JFrame{

FrameDemo (){

Container c = getContentPane ();MyPanel mp = new MyPanel ();c.add (mp);setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);

}public static void main(String args[]){

FrameDemo ob = new FrameDemo ();ob.setSize (600, 200);ob.setVisible (true);

}}

Mr. Vishal Rajput


Recommended