• No results found

Java2 Lab Notes

N/A
N/A
Protected

Academic year: 2021

Share "Java2 Lab Notes"

Copied!
25
0
0

Loading.... (view fulltext now)

Full text

(1)

. 1. Objective: In this section, you will learn to create a simple applet.

2. Equipment:

1- Operating System: Windows XP 2- Software:

Notepad : On Windows machine you can use any simple text editor like Notepad Netbeans :is a Java IDE that is open source

Eclipse : is also a java IDE developed by the eclipse open source community

3.Introduction: Applet is java program that can be embedded into HTML pages. Java applets runs on the java enables web browsers such as mozila and internet explorer. Applet is designed to run remotely on the client browser, so there are some restrictions on it. Applet can't access system resources on the local computer. Applets are used to make the web site more dynamic and entertaining. Applets don't have the main method while in an application execution starts with the main method. Applets can run in our browser's window or in an appletviewer.

3.1An Applet Skeleton:

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

class Myclass extends Applet { public void init() {

/* All the variables, methods and images initialize here will be called only once because this method is called only once when the applet is first initializes */

}

public void start() {

/* The components needed to be initialize more than once in your applet are written here or if the reader

switches back and forth in the applets. This method can be called more than once.*/

}

public void stop() {

/* This method is the counterpart to start(). The code, used to stop the execution is written here*/

}

public void destroy() {

/* This method contains the code that result in to release the resources to the applet before it is

finished. This method is called only once. */ }

public void paint(Graphics g) {

/* Write the code in this method to draw, write, or color things on the applet pane are */

} }

In the above applet you have seen that there are five methods. In which two ( init() and destroy ) are called only once while remaining three (start() , stop() , and paint() ) can be called any number of times as per the requirements.

(2)

Example 1: In this example create a simple applet.

import java.applet.Applet;

public class Javaapplet extends Applet{ public void init() {

}

public void start() { }

public void stop() { }

public void destroy() { }

}

.Output:

Example 2: In this example create a simple applet and show the massage.

package javaapplet;

import java.applet.Applet; import java.awt.Graphics;

public class Javaapplet extends Applet{ String str;

public void init() {

str="This is the simple Applet in java"; }

public void start() { }

(3)

}

public void paint(Graphics g) { g.drawString(str, 10,30); }

public void destroy() { }

}

Output:

Example 3: To Set the background color for applet using the setBackground(Color.BLUE); This

method is used to change the foreground colors of the component.

.

import java.applet.Applet; import java.awt.Color; import java.awt.Graphics;

public class Javaapplet extends Applet{

public void init() {

str="This is the simple Applet in java"; setBackground(Color.BLUE);

}

public void start() { }

(4)

}

public void paint(Graphics g) { g.drawString(str, 10,30); }

public void destroy() { }

}

Output:

Example 3: To set the font color in applet using the setForeground(Color.RED); This method is used

to change the foreground colors of the component.

.

import java.applet.Applet; import java.awt.Color; import java.awt.Graphics;

public class Javaapplet extends Applet{ String str;

public void init() {

str="This is the simple Applet in java"; setBackground(Color.BLUE);

setForeground(Color.RED); }

public void start() { }

public void stop() { }

(5)

public void paint(Graphics g) { g.drawString(str, 10,30); }

public void destroy() { }

}

Output:

Example 4: To set the stat for applet using the showStatus("This is the status in applet ");method.

import java.applet.Applet; import java.awt.Color; import java.awt.Graphics;

public class Javaapplet extends Applet{ String str;

public void init() {

str="This is the simple Applet in java"; setBackground(Color.BLUE);

setForeground(Color.RED); }

public void start() { }

public void stop() { }

(6)

g.drawString(str, 10,30);

showStatus("This is the status in applet "); }

public void destroy() { }

}

Output:

Example 5: in this example we learn to draw a line and set color for line in applet .

import java.applet.Applet;

import java.awt.Color; import java.awt.Graphics;

public class Javaapplet extends Applet{ public void init() {

setBackground(Color.BLUE); }

public void paint(Graphics g) { g.setColor(Color.red); g.drawLine(20,20,150,20); g.setColor(Color.red); g.drawLine(20,20,20,180); } }

Output:

(7)

Example 6: In this section learn circle and fill it .

import java.applet.Applet;

import java.awt.Color; import java.awt.Graphics;

Public class Javaapplet extends Applet{

String str="draw circal in applet"; public void init() {

setBackground(Color.BLUE); }

public void paint(Graphics g) { g.setColor(Color.MAGENTA); g.drawOval(20, 20, 170, 170); g.setColor(Color.GREEN); g.fillOval(20,20, 170, 170); g.setColor(Color.black); g.drawString(str, 50, 100); } }

Output:

(8)

1. Objective: In this section, you will learn set the font size and face of the font.

2. Equipment

1- Operating System: Windows XP 2- Software:

Notepad : On Windows machine you can use any simple text editor like Notepad Netbeans :is a Java IDE that is open source

Eclipse : is also a java IDE developed by the eclipse open source community

3. Introduction:

setFont(Font) - This method is used to change the font of text within a component. Syntax is that:

setFont(new Font("Times New Roman", Font.BOLD,18));

change the font face Mack the selected text bold change the font size

Example 1: In this example set the font size and face.

import java.applet.Applet;

import java.awt.*;

public class Javaapplet extends Applet{

String str="Change the font face and size with (setFont(Font) "; public void init() {

(9)

}

public void paint(Graphics g) { setBackground(Color.blue);

g.setFont(new Font("Times New Roman", Font.BOLD,18)); g.setColor(Color.RED);

g.drawString(str , 50, 50); }

}

Output:

1. Objective: In this section, you will learn how to create Line Drawing. A java program explains the

stroke line how to make thick and thin line.

2. Equipment

1- Operating System: Windows XP 2- Software:

Notepad : On Windows machine you can use any simple text editor like Notepad Netbeans :is a Java IDE that is open source

Eclipse : is also a java IDE developed by the eclipse open source community

3. Introduction:

In this section, you will learn how to create Line Drawing. A java program explains the stroke line i.e. how to make thick and thin line. For this we have used BasicStroke class. This object

is passed to the setStroke() method. Java program uses the setStroke() method. The stroke describes the pen and brush. It is used for drawing the line. This controls all drawing line attribute. It is a suitable of all line drawing needs.

(10)

BasicStroke(): This is a constructor component. A BasicStroke object is used for several different-different line drawing attributes. The BasicStroke() objects are immutable, So its can be safely cached and shared.

Example 1: show the outline of the line.

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

public class DrawLine extends Applet{

Stroke stk = new BasicStroke(4); public void paint(Graphics g) { setBackground(Color.BLUE); Graphics2D ph = (Graphics2D)g; ph.setStroke(stk); ph.setPaint(Color.RED); ph.drawLine(20,20,190,100); } }

Output:

(11)

1. Objective: In this section, you will learn how to display image on the applet.

2. Equipment

1- Operating System: Windows XP 2- Software:

Notepad : On Windows machine you can use any simple text editor like Notepad Netbeans :is a Java IDE that is open source

Eclipse : is also a java IDE developed by the eclipse open source community

3. Introduction:In this section, you will learn how to display image on the applet. In this program,

there are two methods have been used to display the image on the applet in your application. Toolkit class has been used to get the image and then the image is used to display. 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, .jpeg or .png. If the security manager installed then the getImage() method first check whether the specified file name has the permission to use and then retrieves the image in pixels format.

Example 1:

1. Objective: The repaint( ) method is defined by the AWT. It causes the AWT run-time

system to execute a call to your applet’s update( ) method, which, in its default

(12)

implementation, calls paint( ). Thus, for another part of your applet to output to its window, simply store the output and then call repaint( ). The AWT will then execute a call to paint( ), which can display the stored information. For example, if part of your applet needs to output a string, it can store this string in a String variable and then call

repaint( ). Inside paint( ), you will output the string using drawString( ).

The repaint( ) method has four forms. Let’s look at each one, in turn. The simplest version of repaint( ) is shown here:

void repaint( )

This version causes the entire window to be repainted. The following version specifies a region that will be repainted:

void repaint(int left, int top, int width, int height) repaint(long maxDelay)

repaint(long maxDelay, int x, int y, int width, int height) Example 1:

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

public class Lab9 extends Applet { String str;

public void init(){

str="Welcome to java lab class"; setBackground(Color.BLUE); setForeground(Color.RED); }

public void paint(Graphics g){ g.drawString(str, 60, 90); g.drawRect(50,50 ,180,100); repaint(60,100,100,90); update(g); } } Output:

(13)

1. Objective: In this section you well learn event Handlin .

2. Equipment

1- Operating System: Windows XP 2- Software:

Notepad : On Windows machine you can use any simple text editor like Notepad Netbeans :is a Java IDE that is open source

Eclipse : is also a java IDE developed by the eclipse open source community

3. Introduction:

Applets are event-driven programs. Thus, event Handlin is at the core of successful applet programming. Most events to which your applet will respond are generated by the user.

These events are passed to your applet in a variety of ways, with the specific method depending upon the actual event. There are several types of events. The most commonly handled events are those generated by the mouse, the keyboard, and various controls, such as a push button. Events are supported by the

java.awt.event package.

The chapter begins with an overview of Java’s event handling mechanism. It then examines the main event classes and interfaces, and develops several examples that demonstrate the fundamentals of event

processing. This chapter also explains how to use adapter classes, inner classes, and anonymous inner classes to streamline event handling code. The examples provided in the remainder of this book make frequent use of these techniques.

3.1. Introduction:

Events

In the delegation model, 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 cause events to be generated are pressing a button, entering a character via the keyboard, selecting an item in a list, and clicking the mouse. Many other user operations could also be cited as

(14)

examples. Events may also occur that are not directly caused by interactions 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. You are free to define events that are appropriate for your application.

, there are twelve types of event are used in Java AWT. These are as follows : 1. ActionEvent 2. AdjustmentEvent 3. ComponentEvent 4. ContainerEvent 5. FocusEvent 6. InputEvent 7. ItemEvent 8. KeyEvent 9. MouseEvent 10. PaintEvent 11. TextEvent 12. WindowEvent

These are twelve mentioned events are explained as follows :

1. ActionEvent: This is the ActionEvent class extends from the AWTEvent class. It indicates the component-defined events occurred i.e. the event generated by the component like Button, Checkboxes etc. The generated event is passed to every EventListener objects that receives such types of events using the addActionListener() method of the object.

2. AdjustmentEvent: This is the AdjustmentEvent class extends from the AWTEvent class. When the Adjustable Value is changed then the event is generated.

3. ComponentEvent: ComponentEvent class also extends from the AWTEvent class. This class creates the low-level event which indicates if the object moved, changed and it's states (visibility of the object). This class only performs the notification about the state of the object. The

ComponentEvent class performs like root class for other component-level events.

4. ContainerEvent: The ContainerEvent class extends from the ComponentEvent class. This is a low-level event which is generated when container's contents changes because of addition or removal of a components.

5. FocusEvent: The FocusEvent class also extends from the ComponentEvent class. This class indicates about the focus where the focus has gained or lost by the object. The generated event is passed to every objects that is registered to receive such type of events using the addFocusListener() method of the object.

6. InputEvent: The InputEvent class also extends from the ComponentEvent class. This event class handles all the component-level input events. This class acts as a root class for all component-level input events.

7. ItemEvent: The ItemEvent class extends from the AWTEvent class. The ItemEvent class handles all the indication about the selection of the object i.e. whether selected or not. The generated event is passed to every ItemListener objects that is registered to receive such types of event using the addItemListener() method of the object.

8. KeyEvent: KeyEvent class extends from the InputEvent class. The KeyEvent class handles all the indication related to the key operation in the application if you press any key for any purposes of the

(15)

object then the generated event gives the information about the pressed key. This type of events check whether the pressed key left key or right key, 'A' or 'a' etc.

9. MouseEvent: MouseEvent class also extends from the InputEvent class. The MouseEvent class handle all events generated during the mouse operation for the object. That contains the information whether mouse is clicked or not if clicked then checks the pressed key is left or right.

10. PaintEvent: PaintEvent class also extends from the ComponentEvent class. The PaintEvent class only ensures that the paint() or update() are serialized along with the other events delivered from the event queue.

11. TextEvent: TextEvent class extends from the AWTEvent class. TextEvent is generated when the text of the object is changed. The generated events are passed to every TextListener object which is registered to receive such type of events using the addTextListener() method of the object.

12. WindowEvent : WindowEvent class extends from the ComponentEvent class. If the window or the frame of your application is changed (Opened, closed, activated, deactivated or any other events are generated), WindowEvent is generated.

3.2. Introduction: 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. Here is the general form:

public void addTypeListener(TypeListener el) Here, Type is the name of the event and el is a reference to the event listener. For example, the method that registers a keyboard event listener is called

addKeyListener( ). The method that registers a mouse motion listener is called

addMouseMotionListener( ).When an event occurs, all registered listeners are notified and receive a copy

of the event object. This is known as multicasting the event. In all cases, notifications are sent only to listeners that register to receive them. Some sources may allow only one listener to register. The general form of such

a method is this:

public void addTypeListener(TypeListener el)

name of the method reference to the event listener

3.3 Introduction:

Event Listeners

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 methods 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. And MouseListener interface define five methods to receive notifications when mouse clicked, entered , existed , pressed, released. Any object may receive and

(16)

Event Listeners

Every listener interface has at least one event type. Moreover, it also contains a method for each type of event the event class incorporates. For example as discussed earlier, the KeyListener has three methods, one for each type of event that the KeyEvent has: keyTyped(), keyPressed(), and keyReleased(). The Listener interfaces and their methods are as follow:

Interface Methods WindowListener windowActivated(WindowEvent e) windowDeiconified(WindowEvent e) windowOpened(WindowEvent e) windowClosed(WindowEvent e) windowClosing(WindowEvent e) windowIconified(WindowEvent e) windowDeactivated(WindowEvent e) ActionListener actionPerformed(ActionEvent e) AdjustmentListener adjustmentValueChanged(AdjustmentEvent e) MouseListener mouseClicked(MouseEvent e) mouseEntered(MouseEvent e) mouseExited(MouseEvent e) mousePressed(MouseEvent e) mouseReleased(MouseEvent e) FocusListener focusGained(FocusEvent e) focusLost(FocusEvent e) ItemListener itemStateChanged(ItemEvent e) KeyListener keyReleased(KeyEvent e) keyTyped(KeyEvent e) keyPressed(KeyEvent e) ComponentListener componentHidden(ComponentEvent e) componentMoved(ComponentEvent e) componentShown(ComponentEvent e) componentResized(ComponentEvent e) MouseMotionListener mouseMoved(MouseEvent e) mouseDragged(MouseEvent e) TextListener textValueChanged(TextEvent e) ContainerListen er componentAdded(ContainerEvent e) componentRemoved(ContainerEvent e) Example 1: import java.applet.Applet; import java.awt.*;

(17)

import java.awt.event.MouseEvent; import java.awt.event.MouseListener;

import java.awt.event.MouseMotionListener;

public class Lab8 extends Applet implements MouseListener,MouseMotionListener{ int x=0;

int y=0; String str=""; public void init(){

addMouseListener(this);

addMouseMotionListener(this); }

public void mouseClicked(MouseEvent e){ setBackground(Color.BLUE); x=0; y=10; str="Mouse Click"; repaint(); }

public void mouseExited(MouseEvent e){ x=0;

y=10;

str="Mouse Exit"; repaint();

}

public void mouseEntered(MouseEvent e){ x=0;

y=10;

str="Mouse Enter"; repaint();

}

public void mouseDragged(MouseEvent e){ setForeground(Color.RED);

x=e.getX(); y=e.getY(); str="*";

showStatus("Dragging mouse at "+ x +" "+ y); repaint();

}

public void mouseReleased(MouseEvent e){ x=e.getX(); y=e.getY(); str="up"; repaint(); }

public void mousePressed(MouseEvent e){ x=e.getX();

y=e.getY();

str="down"; repaint();}

public void mouseMoved(MouseEvent e){

showStatus("Dragging mouse at "+ e.getX() +" "+ e.getY()); }

(18)

g.drawString(str, x, y); }

}

Output:

public void mouseEntered(MouseEvent e) public void mouseExited(MouseEvent e)

public void mouseReleased(MouseEvent e) public void mousePressed(MouseEvent e)

public void mouseEntered(MouseEvent e) public void mouseClicked(MouseEvent e)

public void mouseDragged(MouseEvent e) public void mouseMoved(MouseEvent e)

(19)

2. Equipment

1- Operating System: Windows XP 2- Software:

Notepad : On Windows machine you can use any simple text editor like Notepad Netbeans :is a Java IDE that is open source

Eclipse : is also a java IDE developed by the eclipse open source community

3. Introduction:

Event Adapters

here are some event listeners that have multiple methods to implement. That is some of the listener interfaces contain more than one method. For instance, the MouseListener interface contains five methods such as mouseClicked, mousePressed, mouseReleased etc. If you want to use only one method out of these then also you will have to implement all of them. Thus, the methods which you do not want to care about can have empty bodies. To avoid such thing, we have adapter class.

Adapter classes help us in avoiding the implementation of the empty method bodies. Generally an adapter class is there for each listener interface having more than one method. For instance, the MouseAdapter class implements the MouseListener interface. An adapter class can be used by creating a subclass of it and then overriding the methods which are of use only. Hence avoiding the implementation of all the methods of the listener interface. The following example shows the implementation of a listener interface directly.

Example 1:

import java.applet.Applet; import java.awt.Color; import java.awt.Graphics; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent;

public class Lab8 extends Applet{ int X, Y;

public void init(){

setBackground(Color.BLUE); addMouseListener(

new MouseAdapter(){

public void mouseClicked(MouseEvent me){ Graphics g = Lab8.this.getGraphics();

g.setColor(Color.red);

(20)

g.drawOval(40,40,me.getX() , me.getY()); } }); }

Output:

1. Objective: In this section, you will learn about the

java.awt.*; package available with JDK.

2. Equipment

1- Operating System: Windows XP 2- Software:

Notepad : On Windows machine you can use any simple text editor like Notepad Netbeans :is a Java IDE that is open source

Eclipse : is also a java IDE developed by the eclipse open source community

3.Introduction: In this section, you will learn about the java.awt.*; package available with JDK. AWT stands for Abstract Windowing Toolkit. It contains all classes to write the program that interface between the user and different windowing toolkits. You can use the AWT package to develop user interface objects. And different components available in the Java AWT package for developing user interface for your program.

Following some components of Java AWT are explained:

(21)

1. Objective: This program shows you how to create a frame in java AWT package.

2. Equipment

1- Operating System: Windows XP 2- Software:

Notepad : On Windows machine you can use any simple text editor like Notepad Netbeans :is a Java IDE that is open source

Eclipse : is also a java IDE developed by the eclipse open source community

3.Introduction: The most common method of creating a frame is by using single argument constructor of the Frame class that contains the single string argument which is the title of the window or frame.

Example 1:

import java.awt.*;

public class Lab8 extends Frame{ public Lab8(){

super();

setSize(300,300); setVisible(true); }

public static void main(String []args){ Lab8 lab=new Lab8();

} }

(22)

Example 2: In this section, you will learn how to implement the close button of any frame or window in

java application.

public class Lab8 extends Frame{ public Lab8(){ super(); setSize(300,300); setVisible(true); setBackground(Color.BLUE); }

public static void main(String []args){ Lab8 lab=new Lab8();

lab.addWindowListener(new WindowAdapter(){ public void mouseClicked(MouseEvent e){ System.exit(0); } } ); } }

Press this button to close the frame

Output:

(23)

Example 3: in this example you learn to set a title for frame

.

import java.awt.*;

import java.awt.event.MouseEvent; import java.awt.event.WindowAdapter; public class Lab8 extends Frame{ public Lab8(){

super();

setSize(300,300); setVisible(true);

setTitle("A sample frame"); setBackground(Color.BLUE); }

public static void main(String []args){ Lab8 lab=new Lab8();

lab.addWindowListener(new WindowAdapter(){ public void mouseClicked(MouseEvent e){ System.exit(0);

} } ); }}

(24)

1. Objective:

2. Equipment

1- Operating System: Windows XP 2- Software:

Notepad : On Windows machine you can use any simple text editor like Notepad Netbeans :is a Java IDE that is open source

Eclipse : is also a java IDE developed by the eclipse open source community

3. Introduction:

In this section you will learn to set an icon to the frame .This program helps us to set the icon(image) on the title bar of the frame. When you open frame or window the icon situated on the title bar. For this purposes as follows has been used: lab.setIconImage(Toolkit.getDefaultToolkit().getImage(“copy.gif)); Above method sets the icon for the frame or window after getting the image using the Image class method named getImage()

Lab.getDefaultToolkit()

This is the method of the Toolkit class which gets the default toolkit.

Example 1:

public class Lab8 extends Frame { public Lab8(){

super();

setSize(300,300); setVisible(true);

setBackground(Color.BLUE); setTitle("A sample frame"); }

public static void main(String []args){ Lab8 lab=new Lab8();

lab.setIconImage(Toolkit.getDefaultToolkit() .getImage("copy.GIF")); lab.addWindowListener(new WindowAdapter(){

public void windowClosing(WindowEvent e){ System.exit(0);

} }); } }

(25)

Output:

References

Related documents

To develop an application using the FTDI Java D2XX for Android driver, the development machine needs the Eclipse IDE and an up-to-date Android SDK, including the ADB

Podjetje je imelo v obdobju pred povišanjem DDV močno negativen neto obratni kapital, vendar so ga pozneje močno izboljšali, zadnji dve leti je bil celo pozitiven, kar pomeni, da

Highly motivated to the zumba fitness instructor resume sample sign in working towards the physical needs in fitness instructors are applying for motivating participants at

The main destination sector for cork products is the Wine Industry, which absorbs 66 per cent of all production, followed by the Building Industry with 21 per

Superior Court of Pennsylvania (1/7/13) No. Investigation led police to the defendant. They removed him to the police station. He was given the warnings before interrogation and he

SHARIFAH MASZURA BINTI SYED MOHSIN, who had given guidance for my work and came up with some inspiring suggestion, in the meantime, his patience in guidance me

(2) Provide foster care benefits (also known as AFDC‐FC benefits) for eligible youth up until the age of 21; 7 (3) Provide extended Kin‐GAP assistance or AAP assistance

Based on the findings and discussion, the researchers concluded that the result of students’ needs analysis of prewriting activities using assisted technology in