V-Game E-Book_En

Page 1


TABLE OF CONTENTS 1.

2.

3.

HTML PROGRAMME .....................................................................................................................................3 1.1.

WHAT IS HTML? ....................................................................................................................................3

1.2.

THE STRUCTURE OF A HTML PAGE ...................................................................................................4

1.2.1.

Basic elements ...............................................................................................................................7

1.2.2.

The structure of a HTML document ..........................................................................................9

1.2.3.

HTML Attributes ...........................................................................................................................9

1.2.4.

HTML Paragraphs and Styles................................................................................................... 10

1.2.5.

Quotations and Citations în HTML ......................................................................................... 12

1.2.6.

Lists and tables ........................................................................................................................... 13

1.3.

THE DIFFERENCE BETWEEN HTML AND HTML5 ......................................................................... 15

1.4.

HTML5 .................................................................................................................................................. 17

1.5.

THE STRUCTURE OF HTML5 ............................................................................................................ 18

THE CASCADING STYLE SHEETS – CSS PROGRAM ................................................................................ 31 2.1.

CSS SYNTAX ......................................................................................................................................... 31

2.2.

CSS UNITS ............................................................................................................................................ 41

THE JAVA PROGRAMMING LANGUAGE .................................................................................................. 44 3.1.

GENERAL FEATURES.......................................................................................................................... 44

3.2.

OBJECTS AND CLASSES ...................................................................................................................... 47

3.3.

THE BASIC ELEMENTS OF THE JAVA PROGRAMMING LANGUAGE ........................................... 49

3.4.

OBJECT & CLASSES IN JAVA .............................................................................................................. 57

3.4.

INPUT STREAMS AND OUTPUT STREAMS ..................................................................................... 77

3.5.

APPLETS .............................................................................................................................................. 83

3.6.

GRAPHICAL INTERFACES.................................................................................................................. 87

REFERENCES: .................................................................................................................................................... 100

2


1. HTML PROGRAMME 1.1. WHAT IS HTML? HTML or the Hyper Text Markup Language is one of the oldest web programming languages and it lays the basis for creating a website. Therefore, before studying other useful Internet programs, it is imperative to be acquainted with HTML as a basic program for creating web pages. Thus, HTML represents a language which can be understood by internet browsers and with its support web pages can be displayed. It can be generated directly using code technologies within the server such as PHP, JSP or ASP. Many applications, such as content management systems, wikis and web forums generate HTML pages. HTML is also used in e-mails as most applications use this type of incorporated editor as a presentation engine to create e-mails. The HTML language offers the following options to the web page creators: 1. To publish documents with headers, texts, tables, lists, photographs, etc; 2. To find information online through the use of hyperlinks by a simple click of the mouse; 3. To draft forms in order to make transactions with servers, to search for information or for commercial types of activities; 4. To insert spreadsheets, videos, sounds and other applications directly into the documents. The HTML editors can be classical editors and the WYSIWYG type of editors (What You See Is What You Get). With the second category of HTML editors the users only handle the graphics and the layout.

1. 2.

The HTML language displays the following advantages: • it is very simple and doesn’t require much time; • it offers absolute control over the creation of a web page; • one can use within the page ”borrowed” HTML code sequences from other web pages. In order to write a HTML program, first it is imperative that we know: What Notepad is and how it is used How to open a file using Internet Explorer or any other browser of your choice What the copy/ paste option is and how to use it The structure of a HTML document is: the HTML version of the document the head area with the tags <head>, </head> 3


3. the body area with the tags <body>, </body> or <frameset>, </frameset> The HTML version can be:  HTML4.01 Strict <!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML4.01//EN” http://www.w3.org/TR/html4/strict.dtd>  HTML 4.01 Transitional <!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional/EN” http://www.w3.org/TR/html4/loose.dtd>  HTML 4.01 Frameset <!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Frameset//EN” http://www.w3.org/TR/html4/framese.dtd>  HTML5 <!DOCTYPE HTML> The most important feature of the language is its portability. When a HTML document is viewed on any computer and on any operating system it will look identical. Interpretation of the document depends on the browser being used.

1.2. THE STRUCTURE OF A HTML PAGE All HTML pages contain tags. The tags are simply markups or labels used by the HTML language along with the texts in order to support the internet browser in displaying the web page content accurately. As with HTML, in HTML5before the elements of the head tag the title tag will be inserted to provide a title for our page. The title of the page must be very short, so that search engines could index words with high value. It is also recommended that an optimization be made with the support of the Search Engine Optimization. Then we will have a more accurate idea about the construction of a site. Optimizing the positioning of the search engines is extremely important if we want people to get acquainted with us and visit our site. For example, if our site intends to advertise for a school, then the title of the page could contain the name of the school. Remember that a correct SEO requires that the title should consist of a number between 10 and 64 characters, including the tracking. This way Google will assign a higher index score and our site will be displayed among the first ones after a search. These words, used in the search, are called keywords and are to be found in the content of the site but also in the HTML code. 4


<!DOCTYPE HTML> <html lang="en-US"> <head> <title>DLEONIDA</title> <meta charset="UTF-8"> </head> <body> <p>My first page</p> </body> </html> The next important element to be introduced between the head tag is the meta element. With the support of this tag the content of the site can be described. <meta name="Description" content=" Photo quality in our country, portrait photos, pictures of landscapes” </>. The description must begin with the title of the site, precisely because search engines consider this tag. According to the SEO, the description must not be shorter that 40 characters, nor longer than 154. This description will be displayed by the search engine in the results. <!DOCTYPE HTML> <html lang="en-US"> <head> <title>DLEONIDA</title> <meta charset="UTF-8"> <meta name="Description" content="Our school is opened to the community" /> </head> <body> <p>Colegiul Tehnic Dimitrie Leonida Petrosani</p> </body> </html>

The meta element allows the attribute name=”Keywords”, an attribute which is not taken into consideration by Google, but is acknowledged by others. <meta name="Keywords" content=" Our school is opened to the community"/> 5


According to the SEO, the length of the ”Keywords” must be between 4 and 8 words or two-word phrases. <!DOCTYPE HTML> <html lang="en-US"> <head> <title>DLEONIDA</title> <meta charset="UTF-8"> <meta name="Description" content="Our school is opened to the community" /> <meta name="Keywords" content=" Scool&community" /> </head> <body> <p>COLEGIUL TEHNIC DIMITRIE LEONIDA PETROSANI</p> </body> </html> Another element which appears in the head tag is the link tag. With its help we can connect different files or sites to our site. For instance, we create a link to a favicon. A favicon is a small photo, usually identical to the logo of the site and it appears before the URL in the browser. <link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" /> Usually, this favicon has a size of 32x32 pixels or 16x16 pixels and 256 colours. <!DOCTYPE HTML> <html lang="en-US"> <head> <title>DLEONIDA</title> <meta charset="UTF-8"> <meta name="Description" content="Our school is opened to the community" /> <meta name="Keywords" content="school&community" /> <link rel="shortcut icon" href="favicon.png" type=”image/x-icon” /> </head> <body> <p>COLEGIUL TEHNIC DIMITRIE LEONIDA PETROȘANI</p> </body> </html> 6


Inside the head tag it is possible to include links to .css files for style and .js files (java script files) which will enhance the aspect of our site.

1.2.1. Basic elements Any HTML page begins with the DOCTYPE declaration which defines the document type as HTML. The DOCTYPE declaration is not case-sensitive. All HML pages contain tags. The tags are simply markups or labels used by the HTML language along with the texts in order to support the internet browser in displaying the web page content accurately. The structure of any HTML page is: <html> <title> </title> <head> </head> <body> </body> </html> All the HTML pages begin and end with the tags <html> and </html> and inside these tags we find the pairs <head>, </head> and <body>, <body>. The <head> tag contains the title of the page between the tags <title> and </title>, descriptions of the <meta> type, styles for the text format, scripts and links to external files (for example scripts, files of the CSS or favicon types). The meta types of tags contain key words, page description, information about the author, useful data for the search engines and display the following format: <META NAME=”name” CONTENT=”content”> Thus we have: • <html></html>begin and finish a HTML page • <title></title>title of the document • <head></head>title of the page • <body></body>body of the page which will show all content In order to write a HTML page we to go through four steps: 1) Open Notepad. 2) Write or copy html code in notepad. 3) Save the page with the name you want and a .html extension. 4) Open the page in a browser. 7


Example:

<html> <title> PAGE`S NAME</title> <head>My First Page</head> </html>

Example: <html> <head> <title>My First Web Page</title> </head> <body> Welcome!<br> In this book we will learn how to create a web page using HTML5. <br> ENJOY! </body> </html> EXERCISE: Create a web page that has your name in the title and insert a sentence of your choice in the body.

8


1.2.2. The structure of a HTML document In this part we talk about:  headings <h1>This is a heading</h1> Link to more information: http://www.w3schools.com/html/tryit.asp?filename=tryhtml_basic_headings  paragraphs In HTML, a paragraph is defined using <p> tag <p>This is a paragraph. </p> More examples: http://www.w3schools.com/html/tryit.asp?filename=tryhtml_basic_paragraphs  links In HTML, a link is defined using <a> tag Link to more information: http://www.w3schools.com/html/tryit.asp?filename=tryhtml_basic_link  images The images are defined using the tag <img> More examples: http://www.w3schools.com/html/tryit.asp?filename=tryhtml_basic_img 1.2.3. HTML Attributes HTML elements can have attributes providing additional information about that element. a) Language attributes An important aspect of HTML5 is declaring, inside a HTML tag, an attribute which indicates the language which the articles in the site are written in: <html lang="ro-RO"> is used to specify Romanian language or <html lang="en-US"> is used to specify English, US dialect. 

<!DOCTYPE HTML> <html lang="ro-RO"> <head> <meta charset="UTF-8"> 9


</head> <body> <p>prima pagina</p> </body> </html> b) Href attributes This attribute is used to specify the link address initially defined by the <a> tag. http://www.w3schools.com/html/tryit.asp?filename=tryhtml_attributes_link c) Size attributes The filename of the source (src), and the size of the image (width and height) are provided by this attribute. <img src=”image.jpg” width=”104” height=”142”> At the following link you can read moreinformation about HTML attributes and tags: http://www.w3schools.com/tags/default.asp 1.2.4. HTML Paragraphs and Styles The HTML <p> element defines a paragraph. The HTML <br> element defines a line break. Use <br> if you want a line break (a new line) without starting a new paragraph The HTML <pre> element defines preformatted text. When we talk about styles, we talk about defining background color, text color, text size and size. For more information please follow the link: http://www.w3schools.com/html/html_styles.asp Useful tags used to set the style and format a html document: <body bgcolor=“red”></body> changes the background color <font color=“green” size=“6” face=“comics sans ms”></font> changes the color, size and font face of the text <center></center> aligns the text to center <left></left> aligns the text to the left <right></right> aligns the text to the right

10


Example: <html> <title> Your name </title> <head> <center>MY FIRST PAGE</center> </head> <body bgcolor=“red”><left> <font size=“6” color=“green” face=“comic sans ms”>WELCOME!<br> We will learn HTMLtogether. This is your first web page! <br> </font></left> </body> </html>

The text can be formatted by using the proper tags. For instance, fonts can be modified in terms of: size, colour, shape (normal, bold, italic), family (Arial, Verdana, etc.), the text can be aligned horizontally or vertically, and the titles (header), from 1 to 6, differ in size (1 being the largest and 6 the smallest). The <div> and </div> tag is used to groups large sections of HTML elements together and format them with CSS. One of the attributes of the div block is align which can take the values: center center text left align text to the left right align text to the right In case we want the inserted text to be displayed exactly as it has been inserted (preformatted text) in the source file we will use the pair of tags <pre> and </pre>. HTML

Display

plain text

plain text

<b>bold text</b>

bold text

<i>italic text</i>

italic text

<u>Underlined text</u>

Underlined text 11


<del>Deleted text</del>

Deleted text

<sup>superscript</sup>

superscript

<sub>subscript</sub>

subscipt

<tt>Monospaced font </tt>

Monospaced font

<cite>Cite</cite>

Cite

<em>Emphasised text</em>

Emphasised text

<code>A piece of computer code </code>

A piece of computer code

<kbd>Defines keyboard input </kbd>

Defines keyboard input

<samp> sample output from a computer program </samp>

sample output from a computer program

<strong>Important text </strong>

Important text

<big>big</big>

big

<small>small</small>

small

<font color="red">red font</font>

red font

<font face="Courier">Courier typeface</font>

Courier typeface

<font size="4">This is size 4</font>

This is Size 4

<div align="center">center-aligned text</div>

center-aligned text

<div align="left">left-aligned text</div>

left-aligned text

<div align="right">right-aligned text </div>

right-aligned text

<h1>Heading 1</h1>

HEADING 1

<h2>Heading 2</h2>

HEADING 2

<h3>Heading 3</h3>

Heading 3

<h4>Heading 4</h4>

Heading 4

<h5>Heading 5</h5>

Heading 5

<h6>Heading 6</h6>

Heading 6

1.2.5. Quotations and Citations ĂŽn HTML A quote is defined using the tag <q>. This way the browser recognizes a quote and inserts quotation marks before and after elements between the <q> tag. A longer quote is usually marked using the tag <blockquote>. <cite> is used to define the title of a work, browsers usually display <cite> elements in italic. 12


1.2.6. Lists and tables Other important tags, apart from those which format the text, are the ones which create lists and tables. Lists are a simple way of organizing the information and can be unordered, ordered and description lists. Unordered lists Unordered lists are delimited by the tags: <ul> and </ul> and the elements by <li> and 

</li>. The elements in the list can be customized using the type attribute which can take the values of square, circle and disc:  list-style-type: disc o list-style-type: circle  list-style-type: square list-style-type: none

Example: <html> <head> <title>My first list page</title> </head> <body> <ul style= ”list-style-type:disc”> <li>apples</li> <li>pears</li> <li>grapes</li> </ul> </body> </html>

13


Ordered lists The ordered lists are delimited by the tags <ol> and </ol> and the elements by <li> and 

</li>. HTML

Display

Examples of fuels: Examples of fuels: <ol> 1. gas <li> gas</li> 2. Diesel fuel <li>Diesel fuel</li> 3. LP gas <li>LP gas</li> </ol>

The elements in the list can be customized using the type attribute which can take the values A (capital letters), a (lowercase letters), I (capital Roman numbers), i (lowercase Roman numbers), 1 (the default option): More information and exercises can be found at the following link: http://www.w3schools.com/html/html_lists.asp Creating tables: These tags are a great utility as tables represent the structure which is the basis of organising web pages. Tables are made of rows and columns, the intersection of which bears the name cells. In order to insert a table, the pair tags <table> and </table> are used, <tr>and</tr> for a row and <td> and </td> for a cell. Tables can be nested, in other words they can contain one or several other tables inside. An example is presented below. The table has: 2 columns and 2 rows, border 1, column 1 with 80px width, column 2 with 160px width, each cell has a different background colour. (bgcolor). HTML

Display

<table border="1"><tr><td width="80" bgcolor="red">red</td><td width="160" bgcolor="yellow">yellow</td></tr><tr><td bgcolor="white">white</td><td bgcolor="green">green</td></tr></table> 14

red

yellow

white green


The attributes of the table tag are: border = border (0 = no border) width = table width height = table height bgcolor = background colour background = background image cellspacing = space between cells cellpadding = space between the margin of cell and content The attributes of the td tag are: align = horizontal alignment of content (left=left, right=right, center=center) valign = vertical alignment of content (top=top, bottom=bottom, middle=middle) width = cell width height = cell height bgcolor = background colour background = background image colspan = merges the cell with the one on its right rowspan = merges the cell with the one bellow HTML

Afisare

<table border="1"><tr><td bgcolor="white">R1 C1</td><td bgcolor="yellow">R1 C2</td><td bgcolor="white">R1 C3</td><td bgcolor="yellow">R1 C4</td></tr><tr><td colspan="2" bgcolor="red">R2 C1+C2</td><td bgcolor="yellow">R2 C3</td><td bgcolor="red">R2 C4</td></tr><tr><td rowspan="2" bgcolor="white">R3 C1 + R4 C1</td><td bgcolor="yellow">R3 C2</td><td bgcolor="white">R3 C3</td><td bgcolor="yellow">R3 C4</td></tr><tr><td bgcolor="red">R4 C2</td><td bgcolor="yellow">R4 C3</td><td bgcolor="red">R4 C4</td></tr></table>

R1 C1

R1 C2

R1 R1 C3 C4 R2 R2 C3 C4

R2 C1+C2 R3 C2

R3 R3 C3 C4

R4 C2

R4 R4 C3 C4

R3 C1 + R4 C1

1.3. THE DIFFERENCE BETWEEN HTML AND HTML5 HTML5 is the latest version of the HTML markup language, and has also received a number due to the innovations it brings. Version 5 is an upgrade which promises greater interactivity for media files (video, audio), offering distinct tags for these. HTML appeared as a markup language in 1990, being standardized in 1997 as HTML4. Since December 2012, the authority called W3C (World Wide Web Consortium) has 15


recommended and supported the use of HTML5 as it creates a better experience for the user and enables the browsers to understand the pages more easily. What are the major differences between HTML and HTML5? 1. HTML5 is no longer a single unit. It represents a collection of applications so that, apart from tags, it also contains API-s (Application Programming Interface) which can interpret each media element distinctively: video, audio, canvas. 2. The Audio and Video files were not part of the HTML4 specifications. On the other hand, HTML5 has created special tags which can manage multimedia elements: [audio] and [video]. 3. Geolocation is almost impossible in HTML4, whereas in HTML5, with the support of JS GeoLocation API it is easy to detect the location of a user who accesses a site. 4. Vector graphics was possible in HTML4 only with the support of applications like Silverlight or Flash. HTML5 contains integral support for vector graphics through the element called [canvas]. 5. As it represents new technology, HTML5 is not supported by all browsers for the time being. This language is still in development and being perfected, so gradually over time other browsers will be able to interpret the new HTML code. 6. To enable search engines to understand the pages better, the [header] and [footer] elements were introduced in HTML5 according to the new web anatomy. 7. Also the [section] and [article] elements were included which will deliver a greater impact in SEO as it will be easier to delimitate certain sections of a text in a page. Once HTML5 was implemented, the role of the Flash platform has diminished considerably as it is no longer necessary in playing videos (its main function). The same will happen to other programs which are used by HTML to render elements which are not supported. What are the reasons why we should use HTML5? 1. Enhanced accessibility due to the recently introduced elements: [section], [article], [header], [footer], [nav], [aside]. Thus people can identify more easily the sections of a text they are interested in. 2. The [!Doctype] declaration is a lot simpler and doesn’t require inserting a long code which can be sometimes misinterpreted. The new declaration is simply [!DOCTYPE HTML] nothing more. 3. The code is easier and more elegant compared to previous versions. 4. Better interaction, as HTML5 is no longer a static language. With the support of the [canvas] element there is the possibility of interacting and creating better animations than with Flash. But more than [canvas], HTML5 brings a series of API-s which will help create a very dynamic site. 5. Creating games. Also with the support of the [canvas] element, one can develop interactive games with functions that are superior to Flash. 16


6. HTML5 has also been adopted by mobile phones’ browsers. There are tags which can support the improvement of a site for the mobile version.

1.4. HTML5 HTML5 represents the fifth revision of the HTML standard, created in 1990 and which has been under development since 2011. It intends to include not only HTML4 but also XHTML1 and DOM2HTML aimed at improving support for the latest multimedia innovations. In HTML5 new tags were added to simplify the introduction of the multimedia files into the page. Among these there are: audio files, video files, graphics, interactive documents etc. Other new elements in HTML5 are: <header>, <nav><figure> and <footer>, each delimitating a specific area. As stated, HTML5 syntax is compatible with HTML4 and XHTML so that: - One can close the elements with a single tag (META, BR, HR, INPUT, IMG) with a slash, <tag />, like in XHTML, or you can leave them without adding a slash,<tag>. - One can use lowercase letters or/and capital letters for the tag names and attributes, thus: <meta charset=”utf-8”> sau <meta charset=”utf-8”/> <img src”image.jpg” alt=”HTML5”> Or: <img src=”image.jpg” alt =”HTML5”> Or, in capital letters: <IMG src="image.jpg" ALT=" HTML5"> Or, in br tag: <br> Or: <BR> Or: <br /> Also, in HTML5, you can choose whether to specify or not the Type attribute in the <script>, and <style>elements: <script type="text/javascript"><!-// Cod JavaScript --></script> 17


Or: <script><!-// Cod JavaScript --></script> <style type="text/css"> /* Cod CSS */ </style> Or: <style> /* Cod CSS */ </style> All these scenarios are valid in HTML5, but for good practice it is recommended that you use the HTML syntax; in other words, use lowercase letters, add the closing slash and specify the "type" attribute in the <script>, and <style> tags.

1.5. THE STRUCTURE OF HTML5 The basic form of a site created with HTML5 is: !DOCTYPE HTML> <html> <body> <p>prima pagina</p> </body> </html>

18


An important aspect of HTML5 is the specification inside a HTML tag of an attribute which indicates the language of the articles written on the site: <!DOCTYPE HTML> <html lang="en-EN"> <head> <meta charset="UTF-8"> </head> <body> <p>first page</p> </body> </html> As with HTML, in HTML5 between the elements of the head tag the title tag will be inserted to provide a title for our page. The title of the page must be very short, so that search engines can index words of high value. It is also recommended that an optimization be made with the support of the Search Engine Optimization. Then we will have a more accurate idea about the construction of a site, optimizing the positioning of the search engines being extremely important if we want people to get acquainted with us and visit our site. For example, if our site intends to advertise for a school, then the title of the page could contain the name of the school. Remember that a correct SEO requires that the title should consist of a number between 10 and 64 characters, including the tracking. This way Google will assign a higher index score and our site will be displayed among the first after a search. These words, used in the search, are called keywords and are to be found in the content of the site but also in the HTML code. <!DOCTYPE HTML> <html lang="en-EN"> <head> <title>DLEONIDA</title> <meta charset="UTF-8"> </head> <body> <p>first page</p> </body> </html>

19


The next important element to be introduced between the head tag is the meta element. With the support of this tag the content of the site can be described. <meta name=”Description” content=”Quality photos only with us, portraits, landscapes”/>. The description must begin with the title of the site, precisely because search engines consider this tag. According to the SEO, the description must not be shorter that 40 characters, nor longer than 154. This description will be displayed by the search engine in the results. <!DOCTYPE HTML> <html lang="en-EN"> <head> <title>DLEONIDA</title> <meta charset="UTF-8"> <meta name="Description" content="Our school is open towards the community" /> </head> <body> <p>Colegiul Tehnic Dimitrie Leonida Petrosani</p> </body> </html>

20


The meta element allows the attribute name=”Keywords”, an attribute which is not taken into consideration by Google, but is acknowledged by others. <meta name="Keywords" content=" Our school is open towards the community"/> According to the SEO, the length of the ”Keywords” must be between 4 and 8 words or twoword phrases. <!DOCTYPE HTML> <html lang="en-EN"> <head> <title>DLEONIDA</title> <meta charset="UTF-8"> <meta name="Description" content="Our school is open towards the community" /> <meta name="Keywords" content=" School open community” /> </head> <body> <p>COLEGIUL TEHNIC DIMITRIE LEONIDA PETROSANI</p> </body> </html>

Another element which appears in the head tag is the link tag. With its help we can connect the different files or sites to our site. For instance, we create a link to a favicon. A favicon is a small photo, usually identical with the logo of the site and it appears before the URL in the browser. <link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" /> Usually, this favicon athe size of 32x32 pixels or 16x16 pixels and 256 colours. 21


<!DOCTYPE HTML> <html lang="en-EN"> <head> <title>DLEONIDA</title> <meta charset="UTF-8"> <meta name="Description" content="Our school is open towards the community " /> <meta name="Keywords" content="school open community" /> <link rel="shortcut icon" href="favicon.png" type=”image/x-icon” /> </head> <body> <p>COLEGIUL TEHNIC DIMITRIE LEONIDA PETROŞANI</p> </body> </html> Inside the head tag it is possible to include links to .css files for style and .js files (java script files) which will enhance the aspect of our site. Organizing a site Organizing a site consists in establishing the way in which the information is displayed on the site. Firstly, the site can have a definite or variable width, respective of the manner in which we want to display the information on the page. As a definite size, the most highly recommended one is 960 pixels as it can be also displayed by some smart phones or tablets. HEADER COLEGIUL TEHNIC DIMITRIE LEONIDA PETROȘANI LOGO

960 px MENU

592px

CONTENT AREA

HOME EDUCATIONALOFFER CONTACT

368px

592px

FOOTER 22


There is also the third possibility of displaying a website, according to the resolution of the screen, in other words, a certain design will be displayed for a phone and another design for a tablet etc. We will further discuss what the body tag should contain and we can insert a block type of element which we will use to group the other elements. This element is <div> and </div>: <!DOCTYPE HTML> <html lang="en-US"> <head> <title>DLEONIDA</title> <meta charset="UTF-8"> <meta name="Description" content="Our school is opened to the community" /> <meta name="Keywords" content="school to community" /> <link rel="shortcut icon" href="favicon.ico" type="image/x-icon" /> </head> <body> <div class=”container”> </div> </body> </html>

Class is a selector used to specify the style of a group of elements. We will introduce a <div class=”header”> in order to create the space in which the div-s containing the title of the site and where the contact information will go: <!DOCTYPE HTML> <html lang="ro-RO"> <head> <title>DLEONIDA</title> <meta charset="UTF-8"> <meta name="Description" content=" Our school is opened to the community " /> <meta name="Keywords" content=” school to community " /> <link rel="shortcut icon" href="favicon.ico" type="image/x-icon" /> </head> <body> <div class="container"> <div class="header"> 23


<div class="contact"> </div> <div class="titlu-site"> </div> </div> </div> </body> </html> Inside <div class="contact"> we will insert two paragraphs with the email address (here we have an id="email" which will result in a correct positioning of the paragraphs) and the phone number, and inside <div class="site-title"> we will insert the title of the site made of the headings h1 and h2. These can range from h1 to h6 and are used only for headings and subheadings. They shouldn’t be used for writing in bold or large fonts. Search engines are interested in the content of the headings, so they must be used wisely: <!DOCTYPE HTML> <html lang="en-US"> <head> <title>DLEONIDA</title> <meta charset="UTF-8"> <meta name="Description" content=" Our school is opened to the community " /> <meta name="Keywords" content=" school to community " /> <link rel="shortcut icon" href="favicon.ico" type="image/x-icon" /> </head> <body> <div class="container"> <div class="header"> <div class="contact"> <p id="email">email: gsdlpetrosani@yahoo.com</p> <p>tel: 0254542482</p> </div> <div class="COLEGIUL TEHNIC DIMITRIE LEONIDA PETROSANI"> <h1>COLEGIUL TEHNIC DIMITRIE LEONIDA</h1> <h2>STR. 22 DECEMBRIE, NR.6, PETROSANI, HUNEDOARA</h2> </div> </div> </div>

24


</body> </html>

We introduced <div class="contact"> first, not <div class="site-title">because <div class="contact"> will be positioned on the left and <div class="site-title"> will be positioned on the right. As a general rule, the first <div> will be the one positioned on the left as this is the "default" setting. Outside <div class="header"> we will insert the menu with a new <div>, made of the <ul></ul> tags (ul from "unordered list") which contains the list created by the <li></li> tags (li from "list"), and containing "bullets" (there is also an "ordered list" with the <ol></ol> tags, inside the <li></li> tags are used, the difference is that numbers will be used and the "definition list" with the <dl></dl> tags to define the elements, inside using <dt></dt> – defines an element in the list and <dd></dd> – describes an element in the list): <!DOCTYPE HTML> <html lang="en-US"> <head> <title>DLEONIDA</title> <meta charset="UTF-8"> <meta name="Description" content="Our school is opened to the community" /> <meta name="Keywords" content="school to community" /> <link rel="shortcut icon" href="favicon.ico" type="image/x-icon" /> </head> <body> <div class="container"> <div class="header"> <div class="contact"> <p id="email">email: gsdlpetrosani@yahoo.com</p> <p>tel: 0254542482</p> </div> <div class="COLEGIUL TEHNIC DIMITRIE LEONIDA PETROSANI"> <h1>LICEU TEHNOLOGIC</h1> 25


<h2>STR. 22 DECEMBRIE, NR. 6, PETROSANI, HUNEDOARA</h2> </div> </div> <div class="meniu"> <ul> <li>HOME</li> <li>ABOUT US</li> <li>CONTACT</li> </ul> </div> </div> </body> </html>

In order to connect the elements of the menu and the pages they refer to, we need links. For this purpose we will use the <a></a> tags , the syntax being as follows: <a href="url">linking text </a> . Consecutively we will insert a button precisely bellow the menu - "call to action" – to draw the visitor’s attention and prompt them to click on it. Now we introduce another <div>, namely the <div class="button"></div>and inside it a link which will link it to the contact.html page: <!DOCTYPE HTML> <html lang="en-US"> <head> <title>DLEONIDA</title> <meta charset="UTF-8"> <meta name="Description" content="Our school is opened to the community" /> <meta name="Keywords" content="school to community" /> <link rel="shortcut icon" href="favicon.ico" type="image/x-icon" /> </head> 26


<body> <div class="container"> <div class="header"> <div class="contact"> <p id="email">email: <a href="mailto:gsdlpetrosani@yahoo.com" title="short description">gsdlpetrosani@yahoo.com</a></p> <p>tel: <a href="tel: phone number without signs" title="short description">+40254542482</a></p> </div> <div class="titlu-site"> <h1>COLEGIUL TEHNIC DIMITRIE LEONIDA</h1> <h2>PETROSANI</h2> </div> </div> <div class="meniu"> <ul> <li><a href="index.html" title="to the home page">home</a></li> <li><a href="about-us.html" title="to the page about us">about us</a></li> <li><a href="contact.html" title="to the contact page">contact</a></li> </ul> <div class="buton"> <a href="contact.html" title="to the contact page.html"></a> </div> </div> </div> </body> </html>

27


A webpage completely created in HTML5 is the following: <!DOCTYPE HTML> <html lang="en-US"> <head> <title>DLEONIDA</title> <meta charset="UTF-8"> <meta name="Description" content="Our school is opened to the community" /> <meta name="Keywords" content="school to community" /> <link rel="shortcut icon" type="image/x-icon" href="favicon.ico" /> <link type="text/css" href="stiluri/css3.css" rel="stylesheet" /> </head> <body> <div class="container"> <div class="header"> <div class="contact"> <p id="email">email: <a href=mailto:gsdlpetrosani@yahoo.com title="shortdescription">gsdlpetrosani@yahoo.com</a></p> <p>tel: <a href="tel: phone number" title="short description">+40254542482</a></p> </div> <div class="site title"> <h1>COLEGIUL TEHNIC DIMITRIE LEONIDA</h1> <h2>PETROSANI</h2> </div> </div> <div class="meniu"> <ul> <li><a href="index.html" title="to home page">HOME</a></li> <li><a href="about-us.html" title="to the about-us page">ABOUT US</a></li> <li><a href="contact.html" title="to the contact page">CONTACT</a></li> </ul> <div class="buton"> <a href="contact.html" title=" to the contact page.html"></a> </div> </div> <div class="content"> <div class="pikachoose"> <ul id="pikame" class="jcarousel-skin-pika"> <li><img alt="imaginea 1" src="imagini/posa1.jpg"/></li> 28


<li><img alt="imaginea 2" src="imagini/posa2.jpg"/></li> <li><img alt="imaginea 3" src="imagini/posa3.jpg"/></li> <li><img alt="imaginea 4" src="imagini/posa4.jpg"/></li> <li><img alt="imaginea 5" src="imagini/posa5.jpg"/></li> </ul> </div> </div> <div class="footer"> <p>© <a href="mysite" title="tom y site"> my site</a></p> </div> </div> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.js "></script> <script type="text/javascript" src="js/jquery.jcarousel.min.js"></script> <script type="text/javascript" src="js/jquery.pikachoose.js"></script> <script> $(document).ready( function (){ $("#pikame").PikaChoose({carousel:true,carouselOptions:{wrap:‘circular’}}); }); </script> </body> </html>

29


This page can be tested at: http://validator.w3.org/#validate_by_input

30


2. THE CASCADING STYLE SHEETS – CSS PROGRAM A Cascading Style Sheet (CSS) describes how a HTML page is to be displayed in a distinct document. CSS has the following advantages: – It allows the separation of document content from document presentation. – It makes it possible to define the presentation and layout of all the pages on a website in a single location. – It can be used for both HTML and XML pages. CSS has also a disadvantage: – It is not entirely supported by some browsers.

2.1. CSS SYNTAX CSS syntax is simple – it is a file which contains a list of selectors (to select the tags) and descriptors (to specify what we intend to do with the respective tags): – Example: h1 {color: green; font-family: Verdana} it specifies that anything included in h1 tags(HTML heading level 1) must be displayed using the Verdana type of font and the colour green A CSS file represents a list of such selector/descriptor pairs – The selectors can be simple HTML or XML tags, but CSS also allows the definition of other ways of combining tags – The descriptors are defined precisely in CSS The general syntax is: selector { property: value } or selector, ..., selector { property: value; ... property: value } – where: • the selector represents the tag which is affected by style (the selector is case-sensitive only if the description language of the document is case-sensitive) 31


• property and value describe the display mode of the respective tag • The spaces after commas or semicolons are optional • A semicolon must be used between property: value pairs, but after the last pair the semi colon becomes an optional character

Example of a CSS • /* This is a comment */ • h1,h2,h3 {font-family: Arial, sans-serif;} /* use 1st available font */ • p, table, li, address { /* apply to all these tags */ font-family: "Courier New"; /* quote values containing spaces */ margin-left: 15pt; /* specify indentation */ } • p, li, th, td {font-size: 80%;} /* 80% of size in containing element*/ • th {background-color:#FAEBD7} /* colors can be specified in hex */ • body { background-color: #ffffff;} • h1,h2,h3,hr {color:saddlebrown;} /* adds to what we said before */ • a:link {color:darkred} /* an unvisited link */ • a:visited {color:darkred} /* a link that has been visited */ • a:active {color:red} /* a link now being visited */ • a:hover {color:red} /* when the mouse hovers over it */ SELECTORS An XML or HTML tag can be used as a simple selector element: body { background-color: #ffffff } We can also use multiple selectors: em, i {color: red} We can repeat the selectors: h1, h2, h3 {font-family: Verdana; color: red} h1, h3 {font-weight: bold; color: pink} When the values do not coincide, the last declaration will overwrite the previous declarations. The universal selector * applies to any type of element and all elements: * {color: blue} When the values do not coincide, the more specific selectors overwrite the behaviour of the more general selectors (so the em elements will consequently be red).

32


Example of overwriting

A descendant selector will select a tag with an appropriate ancestor: – p code { color: brown } – selects code if it is used within a paragraph A child selector > will choose a tag with an appropriate parent: h3 > em { font-weight: bold } it selects an em only if the immediate parent is h3 An adjacent selector chooses an element which immediately follows another: b + i { fontsize: 8pt }

Example:<b>I'm bold and</b><i>I'm italic</i> The result will be displayed as follows: I'm bold and I'm italic

Example: <html> <head> <title>HTML/CSS Styles Overwriting Test</title> <style TYPE="text/css"> body { background-color: #ffffff } em, i {color: red} h1, h2, h3 {font-family: Verdana; color: red} h1, h3 {font-weight: bold; color: pink} * {color: blue} </style> </head> 33


<body> <p>We used the following CSS styles, in this order:</p> <em>em {color: red}</em><br> <b>b {color: blue}</b><br> <h3>h3 {font-family: Verdana;font-weight: bold; color: pink}</h1> <h2>h2 {font-family: Verdana; color: red}</h2> <h4>h4 {color: blue}</h4> </body> </html>

A simple attribute selector enables the selection of the element which possesses a certain attribute, regardless of its value: – Syntax: element[attribute] { ... } – Example: table[border] { ... } An attribute selector allows the selection of the elements with a certain attribute of a specific value: – Syntax: element[attribute="value"] { ... } – Example: table[border="0"] { ... }

34


Example: <html> <head> <title>HTML/CSS Test Selectors</title> <style TYPE="text/css"> p code { color: green } h3 > em { color: red; font-weight: bold } b + i { font-size: 8pt } </style> </head> <body> Code sequence: <code>if (x ==0) exit(1); </code><br> <p><code>if (x ==0) exit(1); </code></p> <p><i><code>if (x ==0) exit(1); </code></i></p> <h3><em>Child</em></h3> <h3><u><em>Grandchild</em></u></h3> <p><b>Text Bold</b><i>Text italic</i><i>Text italic</i></p> <p><i>Text italic</i><b>Text Bold</b></p> </body> </html>

35


VALUES The syntax of a CSS rule is: selector, ..., selector { property: value; . . . property:value } The value represents anything displayed between colon and semi colon (or accolade)

Example: * {font-family: Trebuchet, Verdana, sansserif;} – This means that the Trebuchet font must be used for everything, if it is available; otherwise one can use any sans serif font employed by the browser. • section {border: thin solid blue;} – It means that a border must be added around the section elements; the border must be thin and solidand blue. THE CLASS ATTRIBUTE The class attribute allows the existence of multiple different styles for the same element In the “style sheet” file: p.important {font-size: 24pt; color: red} p.fineprint {font-size: 8pt} – In HTML: <p class="important">The end is nigh!</p> <p class="fineprint">Offer ends 1/1/97.</p> To define a selector which applies to any element which has a certain class the name of the tag is omitted (but the full stop is kept): .fineprint {font-size: 8pt} THE ID ATTRIBUTE The id attribute is defined similarly to the class attribute, but uses # instead. – In the style sheet: p#important {font-style: italic} or # important {font-style: italic} – In HTML: <p id="important"> class and id can be both used and it is not necessary to have different names: <p class="important" id="important"> 36


DIV AND SPAN Div and Span are HTML elements whose single purpose is to maintain CSS information, div ensures the existence of a new line break before and after (similarly to a paragraph); span doesn’t.

Example: – CSS: div {background-color: #66FFFF} span.color {color: red} – HTML: <div>This div is treated like a paragraph, but <span class="color">this span</span> is not.</div> THE USE OF STYLE SHEETS • • • • • • • •

There are three ways of using a CSS: – Style sheet external The strongest approach It applies for both HTML and XML All the CSS elements can be used – Style sheet embedded It applies only for HTML, and not for XML All the CSS elements can be used – Styles inline It applies only for HTML, and not for XML The limited form of CSS syntax

EXTERNAL STYLE SHEETS In HTML, inside the element <head>: <link REL="STYLESHEET" TYPE="text/css" HREF="Style Sheet URL"> In the prologue of an XML document: <?xml-stylesheet href="Style Sheet URL" type="text/css"?> Note: "text/css" represents the MIME type

37


EMBEDDED STYLE SHEETS In HTML, inside the element <head>: <style TYPE="text/css"> <!-CSS Style Sheet --> </style> Note: The embedding of the style sheet in a comment represents an attempt to hide the information from older browsers which do not understand the CSS syntax. INLINE STYLE SHEETS The STYLE attribute can be added to any HTML element: <html-tag STYLE="property: value"> or <html-tag STYLE="property: value; property: value; ...; property: value"> Advantage: – it is useful if we aim at a minor change of style Disadvantages: – A mixture of display information in HTML – It hides and diminishes the visibility of the HTML code – One cannot use all the CSS elements THE CASCADING ORDER The styles will be applied to HTML in the following order: 1. The default style of the browser 2. External style sheet 3. Internal style sheet (inside the <head> tag) 4. Inline style (inside other elements, the outer ones first) When the style elements reach a conflict, the “closest” style (the most recently applied) wins.

38


Example of cascading order • External style sheet: h3 { color: red; text-align: left; font-size: 8pt } • Internal style sheet: h3 { text-align: right; font-size: 20pt } • Resulting attributes: color: red; text-align: right; font-size: 20pt

Example: CSS chapter {font-family: "Papyrus", fantasy} foreword > paragraph {border: solid red; padding: 10px} novel > foreword {font-family: Impact; color: blue} chapter {display: block} chapter:first-letter {font-size: 200%; float: left} paragraph {display: block} chapter:before {content: "New chapter: "} Result

39


SOME FONT PROPERTIES AND VALUES • font-family: – inherit (similar to the font of the parent element) – Verdana, "Courier New", ... (if the font is installed on the client terminal) – serif | sans-serif | cursive | fantasy | monospace (Generic: the browser decides on the selection of the font) • font-size: – inherit | smaller | larger | xx-small | x-small | small | medium | large | x-large | xx-large | 12pt • font-weight: – normal | bold |bolder | lighter | 100 | 200 | ... | 700 • font-style: – normal | italic | oblique THE SIMPLIFIED FORM OF THE PROPERTIES Often several properties can be combined: h2 { font-weight: bold; font-variant: smallcaps; font-size: 12pt; line-height: 14pt; fontfamily: sans-serif } It can be written as: h2 { font: bold small-caps 12pt/14pt sans-serif } COLOURS AND LENGTHS • color: and background-color: – aqua | black | blue | fuchsia | gray | green | lime | maroon | navy | olive | purple | red | silver | teal | white | #FF0000 | #F00 | rgb(255, 0, 0) | Additional browser-specific names (not recommended) These are elements used for measurement units: – em, ex, px, % • The size of the font, the x-height, pixels, percentage of the inherited size – in, cm, mm, pt, pc. • inches, centimetres, millimetres, points (1/72 in an inch), picas (1 pica = 12 points), relative to the inherited value. SEVERAL TEXT PROPERTIES AND VALUES • text-align: – left | right | center | justify • text-decoration: – none | underline | overline | line-through • text-transform: – none | capitalize | uppercase | lowercase • text-indent – length | 10% (indenting the first line of a text) 40


• white-space: – normal | pre | nowrap PSEUDO-CLASSES Pseudo-classes are elements whose state (and display) can differ in time. Syntax: element:pseudo-class {...} – :link An unvisited link – :visited A visited site – :active Alink being clicked on – :hover A link with the mouse hovering over it. Pseudo-classes are allowed anywhere within the CSS selectors. SELECTING NAMES CSS has been projected to separate the content from the style – Consequently, the names which are used inHTML or (particularly) in XML must describe thecontentnot the style.

Example: – Let us assume that you define span.huge {font-size: 36pt} and use <span class="huge"> within several documents. – Later you discover that the users disagree with this style, so you change the CSS into span.huge {font-color: red} – The name has been selected incorrectly. Would you try to redefine it in all the documents? – If you had chosen span.important {font-size: 36pt} from the very beginning, your own documents would have been more obvious and easier to manage.

2.2. CSS UNITS For many of the CSS values remaining we must specify measurement units. – These are used to define size: • em the length of the letter ‘m’ 41


• ex the height of the letter ‘x’ • px pixels (usually 72 per inch, depending on the screen) • % percentage of the inherited size – They are also used to define size, but are meaningless unless the screen resolution is acknowledged: • in inches • cm centimetres • mm millimetres • pt points (72pt = 1in) • pc picas (1pc = 12pt) Note: you can use decimal fractions, such as 1.5 cm. PADDING The padding represents the extra space around an element, but inside the border. To set the padding, use any or all of the following: – padding-top: size – padding-bottom: size – padding-left: size – padding-right: size – padding: size • size is represented with the units described earlier

Example: sidebar {padding: 1em; padding-bottom: 5mm} BORDERS You can set the attributes of the border with any or all of the following: border-top:, border-bottom:, border-left:, border-right:, and border: The attributes are: – The width of the border: thin, medium (default), thick, or a specific size (e.g. 3px) – The style of the border: none, dotted, dashed, solid, double, groove, ridge, inset, or outset – The colour of the border: one of the 16 predefined colours or a hex value of #rrggbb or rgb(r, g, b) or rgb(r%, g%, b%)

Example: section {border-top: thin solid blue;} 42


Note: special styles (such as groove) are not as cool as they sound. MARGINS The margins are the extra space outside the border. Margins can be set similarly to paddings. To set the margins, use any or all of the following: – margin-top: size – margin-bottom: size – margin-left: size – margin-right: size – margin: size BOX AND DISPLAY INTERACTIONS • With display:none, contents are invisible and margin, border, and padding settings have no effect. • With display:block, margin, border, and padding settings work about as you would expect. • With display:inline (which is the default if you don’t specify otherwise): – Margin, border, and padding settings for left and right work about as you would expect – Margin, border, and padding settings for top and bottom do not add extra space above and below the line containing the element This means that inline boxes will overlap other text. CREATING A CONSISTENT LOOK      

Everypage of the site should share some style elements with the other pages; The user should be unconsciously aware that he is still surfing the same site; The same logo or set of buttons must be used in every page; A consistent colour scheme and set of fonts are used; The pages shouldn’t appear identical, but they must have the same style; The CSS style sheets can be of great help in creating a consistent style but tests should be run on a variety of browsers.

43


3. THE JAVA PROGRAMMING LANGUAGE 3.1. GENERAL FEATURES The JavaScript language was developed by Netscape and Sun and it was designed as a language which extended the programming possibilities of HTML. It works with HTML. Java can be used for the following levels: The client level When Java has to run on a client machine it is typically implemented within a miniapplication run from the navigator, which can communicate with the server it was downloaded from. The application server level Java can be used on the application server to implement shared and recyclable components which are rendered by the logics of the application. Java can also be used for this intermediate level to provide control interfaces for applications generated as web pages. The data server level This server stores data but it can also store and execute Java code.Particularly, this code manipulates data intensively or restricts data input by using validation rules. Characteristics of the JavaScript language:  In JavaScript one can write program sequences called scripts. Most of these sequences are made of functions corresponding to certain events.  In JavaScript one CANNOT read or write files.  JavaScript is an interpreted language. This means that when the browser is given an instruction, it executes it. Then it receives another instruction, it executes this and so on.  JavaScript is a language which uses objects.  In JavaScript the distinction between uppercase and lowercase letters is clear, in other words, it is case sensitive.  Syntax errors are hard to detect, consequently one can use the alert function ( ).  It uses some of the C++ syntax and Java language  JavaScript works with functions defined by programmers or with/and predefined functions There are three ways of writing in an HTML document:  The script is written in head; .<script language=”JavaScript” > and</script>;  The script is written in body; .<script language=”JavaScript” > and</script>;  The script appears as externalfile with js extension, so “name.js”; 44


<script src = “name.js ”> and</script> The advantages of Java • It is object-oriented. The object is an entity characterized by attributes and a set of functions used to manipulate the object • Interpreted and platform independent - Java programs can run under any operating system • Dynamic and distributed – Java classes can be dynamically downloaded through the network when necessary • With multiple execution threads – Java programs can contain several threads in order to execute multiple tasks simultaneously • Robust and secure - Java possesses internal facilities to prevent corruption of memory There are several steps in developing a Java program:  Editing the program in a text editor  Saving the program under the name ClassName.java where ClassName is the name of the class containing the main method. In a Java program there must be a single class containing a main method(). In other words, the name of the class must be identical tothe name of the file. The extension the file is .java  Compiling the program with the help of the command javac ClassName.java  Running the program with the help of the command java ClassName

Example: 1. Writing the source code: class Hello { public static void main( String args[]) { System.out.println("Hello !!!"); } } All Java applications contain a main class in which the main() method must be found. The classes of the application can be found in either a single file or in several files.

45


2. Saving the source files This will be done in files with the .java extension. The file containing the source code of the main class must have the same name as the main class of the application (the class which contains the main method). Consequently, our file will be saved under the name: Hello.java 3. Compiling the application The Java compiler is used, javac. The compiler is invoked for the file containing the main class of the application. The compiler creates a separate file for every class of the program; they have the .classextension and are placed within the same director as the source files. The result of the command javac Hello.java is the file Hello.class 4. Running the application It can be performed with the java interpreter, invoked for the compiling unit corresponding to the main class, but omitting the .class extension associated with it. java Hello Running an application which doesn’t use graphic interface is to be performed within a system window.

Example Creating the file structure and compiling the applets are identical as in the case of applications. However, the structure of the program and its way of running differs. 1. Writing the source code: import javax.swing.*; import java.awt.*; public class Hello extends JApplet { public void paint(Graphics g){ g.drawString("Salut",50,50); } } 2. Saving source files Will be performed in the file Hello.java 3. Compiling the applet javac Hello.java As a result of compiling the applet the Hello.class file appears 46


4. Running the applet Applets do not run independently. They can be run only through a browser: Internet Explorer, Netscape or a special program such as the applet viewer in the JDK set. Creating an HTML file for a mini-application (example.html) <html> <head> <title>First Applet Java</title> </head> <body> <applet code=Hello.class width=400 height=400> </applet> </body> </html> 5. Viewing the applet appletviewer example.html For more informations:http://www.w3schools.com/js/js_syntax.asp

3.2. OBJECTS AND CLASSES Object – oriented programming is inspired by the real world – the objects are often made of several types of smaller objects. When writing programs in an object – oriented language, we do not define objects but classes of objects, where a class represents a template pattern for multiple objects with similar characteristics. Classes display all the characteristics of a particular set of objects. The object or class instance represent the same concept. The class is the general representation of an object and the instance/object is the specific representation of the class. Every class written in Java has two main characteristics: attributes and behaviour. Attributes create distinction between objects and determine the appearance, state or other qualities of the object in question. If we intend to create a Car class, it should include the following attributes: color, style and make. Attributes are defined in classes as variables. The type and name of variables are defined in classes and each object has its own values for every attribute. As every class instance can possess different values for its variables, these variables are also called instance variables.

47


Example: An instance of the car class, MyCar could have the following values for its attributes: colour = white style = elegant make = Mercedes There are also variables called class variables. The values of the instance variables are kept within the instances and change for every instance and the values of the class variables are kept in the class and do not change for every instance. The behaviour of a class determines how an instance of a class operates. For example the behaviour of a car consists of: starting and stopping the engine, brakes, change of speed and direction, etc. In order to define the behaviour of a class, methods are defined, the equivalent of the functions or procedures in other programming languages. Unlike other programming languages, in Java it is not possible to define functions without classes. Somethods are functions defined within the classes which work in the instances of the respective classes. The method of an object can be invoked by another object or class. As in the case of attributes, there are two types of methods: instance methods and class methods. Instance methods run only within the instance of a class. On the other hand, class methods work within the class. The principles of object-oriented programming The object is a variable which possesses a structure and a state. Every object displays operations through which its state can be manipulated. The user doesn’t have direct access to the constituent parts of an object or its implementation; these can only be accessed through the methods which had been provided with the object. Grouping the data and the operations which can be performed with this data, while maintaining the implementation details remain hidden, is called encapsulation. One of the main goals of the object – oriented programming is to reuse the code. Object – oriented languages provide several mechanisms for this purpose. 1. Use of the generic code – if the implementation is identical and only the basic type of the object is different, it is not necessary to rewrite the code entirely – one can write a generic code which functions for any type. For example, one can write a method which orders a set of integers, characters or sets of characters. 2. Inheritance is a mechanism which allows the extension of class functionality. It is possible to created new types of data which would extend (or restrict) the properties of the original type of data. 48


3. Polymorphism A type of polymorphic reference can treat several types of objects. When the polymorphic type of method is invoked, one will automatically select the method corresponding to the type treated at the moment.

3.3. THE BASIC ELEMENTS OF THE JAVA PROGRAMMING LANGUAGE Identifiers Identifiers are unlimited sequences of letters and Unicode numbers and must begin with a letter. The identifiers must not be identical to the reserved keywords. Constants Constants can be of the following types 1. Integer constants 2. Real constants 3. Logical (Boolean) constants 4. Character type constants Predefined escape sequences in Java: Cod \u0008 \u0009 \u000a \u000c \u000d \u0022 \u0027 \u005c \u0008

Secvenţa Escape '\b' '\t' '\n' '\f' '\r' '\"' '\'' '\\' '\b'

Caracter Backspace(BS) horizontal tab (HT) Line Feed (New Line) (LF) Formfeed (FF) Carriage Return (CR) Double Quote Single Quote Backslash Backspace(BS)

5. String Constants A string consists of zero or more characters between single or double quotes. For more information please go to http://www.w3schools.com/js/js_objects.asp Separators A separator is a character which indicates the end of a lexical unit and the beginning of another one. In Java, separators are: ( ) { } [ ] ; , . Program instructions (statements) are always separated by ”;”. 49


Operators 1. Simple assignment operator: = (sign equal) 2. Arithmetic operators:+, -, *, /, % Assignment operators:+=, -=, *=, /=, %=

Example:n += 2 means that n=n+2 3. Unary arithmetic operators:++ (increment), -- (decrement). These types of operators can be prefixed (++x or --x) or postfixed (x++ or x--). 4. Logical operators:&&(and), ||(or), !(not) Note: the evaluation of the logical expression is done by short circuiting (evaluation stops when the true/false state of the operation is found) 5. Comparison operators:<, <=, >, <=, ==, != 6. Bitwise operators:& (and), |(or), ^(xor), ~(not) 7. Shift operators:<<, >>, >>> (translate to the right without sign) 8. Conditional (Ternary) Operator: �? : � . Has the syntax: logical_expression ? expression1 : expression2 The value of expression is expression1 if logical_expression is true or expression2 if logical_expression is false.

Example: Method for calculation of the minimum of two numbers is: public int min (int a, int b){ return a<b?a:b; } 9. operator , (comma) is used for the sequential evaluation of the operations.

Example:int x=0, y=1, z=2; 10. operator + is also used for string concatenation: 11. Type conversion operator (cast) is: (type_of_data) int i = 200; long l = (long)i; //conversion thru extension long l2 = (long)200; int i2 = (int)l2; // conversion thru contraction For more information please go to http://www.w3schools.com/js/js_operators.asp

50


Comments In Java there are three types of comments:  Single line comments: start with //.  Multi-line comments, any block of text enclosed between /* and */.  Multi-line comments of documentation type, any block of text between /** and **/. All the text between the two sequences is automatically moved to the application documentation by the automated documentation generator javadoc. Notes: 1. Comments inside other comments cannot be written. 2. Comments cannot be added inside character or string type constants 3. Sequences /* şi */ can appear on the same line with sequence // but loose their significance; the same happens to sequence // in comments beginning with /* or /**. For more information please go to http://www.w3schools.com/js/js_comments.asp Data types In Java there are two main categories of data:  Primitive Data Types  Reference/Object Data Types Primitive Data Types: 1. Integer type Data type Size in bytes byte 1 short 2 int 4 long 8

Range -128 .. 127 -32768 .. 32767 -2147483648 .. 2147483647 -263 .. 263-1

2. Real type Data type Size in bytes Range float 4 -1046 .. 1038 double 8 -10324 .. 10308 3. Char data type: a single 16 bit (2 bytes) Unicode character 4. Boolean type: has two possible values – true and false Arrays, class objects and interface are Reference/Object Data Types. The value of this type of data is always a reference (memory address) to the value or set of values taken by that variable. A reference data type can be used to refer to any object of the declared type or any compatible type. For more information go to http://www.w3schools.com/js/js_datatypes.asp 51


Variables Variables are a container for storing data values, which can be a primitive type of data or a reference to an object. Declaring (creating) variables is done with the syntax: type_of_data variable_name Initialize (assign a value) variables is done with the syntax: variable_name = value You can also assign a value to the variable when you declare it: type_of_data variable_name = value Creating constants is done using the syntax: final type_of_data variable_name

Examples: itnt a; a=5; final double PI = 3.14; int value = 100; long numberofElements = 12345678L; String flower = "daisy"; Based on where a variable is defined, it can be: 1. Instance variables, are declared in a class, but outside a method, constructor or any block.Theyare visible for all methods, constructors and block in that class, and also for other classes but should be called using the fully qualified name. 2. Local variables, are declared inside a method, constructor or block and are visible only within the declared method, constructor or block. For more information go to http://www.w3schools.com/js/js_variables.asp Statements a. Empty statement It looks like this: ”;”. b. Conditional statements 1. The conditional if–elsestatement has the syntax: if (logical_condition) code1 else code2 other code 52


If logical_condition has the value true then code1 is executed, otherwise code2 is executed. Logical_condition must be between brackets. If more a block of code is written it has to be between accolades {…}. The else code2 part can be absent. 2. Switch statement has the syntax: switch (expression){ case val_1: code_1; break; case val_2: code_2; break; ... case val_i: code_i; break; ... case val_n: code_n; break; default: code; } This is how it works: The switch expression is evaluated once, the value of the expression is compared with the values of each case (val_1, val 2, …, val_n). If there is a match (expression=val_i) the associated block of code is executed, otherwise the default block of code is executed. When the break keyword is reached, it breaks out of the current switch block. If the break keyword is missing, then all the codes are executed until the first break is encountered. For more information go to http://www.w3schools.com/js/js_switch.asp c. Loops 1. Loops through a block of code a number of times while a condition is true. Generally the number of times the block of codes is to be executed is known. The syntax of the statement is: for (set; condition; increment) code to be executed where:  set is executed before the loop (the code block) starts and it is used to initiate the variable used in the loop (i = 0)  condition is a boolean expression used to evaluate the condition for running the loop (the code block). If its value returns true, the loop will start over again, if it returns false, the loop will end.  incrementincreases the initial variable. Any of the three (set, condition or increment) can be omitted. for ( ; ; ) 53


In this case we have an endless loop. In order to avoid this, a stopping condition has to exist in the block of code. For more information go to http://www.w3schools.com/js/js_loop_for.asp 2. While loop has the syntax: while (condition) code to be executed The while loop loops through a block of code as long as a specified condition is true. The while loop is also called an initial test statement. If at the first evaluation the specified condition if false, the block of code is never executed. For more information go to http://www.w3schools.com/js/js_loop_while.asp 3. Do-while loop has the syntax: do{ code block to be executed }while (condition); The do-while loop is a variant of the while loop, and it is used to loop through a block of code as long as a specified condition is true. The difference is that do-while will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true compared to the while loop where the condition is evaluated first. The do-while loop is also called a final test statement. 4. Break statement break The break statement is used to forcefully "jump out" of a loop statement (for, while, dowhile). 5. Continue statement It breaks one (the current) iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop. Note: The continue statement can appear only in repetitive loops, but the break statement can also appear in a switch statement as well. For more information go to http://www.w3schools.com/js/js_break.asp

54


Displaying arrays a. One-dimensional arrays Creating an array is done like so: TypeElement[ ] nameArray; or TypeElement nameArray[ ]; where TypeElement is the type of the items inside the array, while the brackets [ ] which can be in front or after the name, show us it is an array.

Example: int[ ] integer_numbers; String location[ ]; Assign values to an array can be done with the keyword new; it allocates the memory needed to memorize the elements of the vector, specifically defining the maximum elements the array will hold. The syntax is the following: nameArray = new TypeElement[maximum_size];

Example: v = new int[10]; //allocate space for an array of 10 integer numbers location = new String[100]; //allocates space for 100 strings Creating and assigning values to an array can be done in one instance, using the syntax: TypeElement[ ] nameArray = new TypeElement[maximum_size]; After creating an array, this can be assigned values to, meaning its elements can have values defined. In this case the memory allocation is done automatically based on the number of elements the vector had when created.

Example: String colors[] = {"Red", "Yellow", "Green"}; int []v = {2, 4, 6, 8, 10, 12}; Note: The first index value of an array is always 0, so a specific position inside an array with n elements will be between 0 and n-1. Syntaxes like bellow are not allowed: TypeElement nameArray[maximum_size] 55


As memory allocation is done only by using the keyword new or automatically.

Example: int v[10]; //not correct int v[ ] = new int[10]; //correct Access the elements of an array is one via the syntax: nameArray [index]

Example 1: int v[]=new int[10]; for(i=0; i<10; i++) v[i]=i; b. Multidimensional arrays (Matrixes) In Java multidimensional arrays are actually arrays of arrays. This means that creation, display and value assigning is done the same way as for one-dimensional arrays. TypeElement nameArray [][]… = new TypeElement[size1][size2]… or TypeElement[][]… nameArray = new[size1][size2]… TypeElement Where the brackets can be either before or after of name is used Array.

Example: int m[][]; m = new int[5][10];

//creating a matrix //with 5 lines, 10 columns

Note: m[0], m[1], ..., m[5] are arrays of integer with 10 elements Length of an array The length property of an array returns the length of an array (the number of array elements).

Example: Given the array int []a = new int[5]; then a.length has a value of 5. 56


Given the matrix int m = new int[5][10]; then: m.length has the value of 5 and it represents the number of lines of the matrix, m[0].length has the value 10 and it represents the number of elements of the first line of the matrix, m[1].length has the value 10 and it represents the number of the second line of the matrix, etc. For more information go to http://www.w3schools.com/js/js_arrays.asp Strings In Java, a string can be represented by an array of char type elements, an object of the type String or StringBuffer.

Examplesof creating a string: String str = "abc"; char data[] = {'a', 'b', 'c'}; String str = new String(data); String str = new String("abc"); String concatenation is done with the operator +. String str1 = "abc" + "xyz"; String str2 = "123"; String str3 = str1 + str2; In Java, the concatenation operator + is very flexible, allowing strings of objects of any type to be concatenated, as long as they are of type char. For more information go to http://www.w3schools.com/js/js_datatypes.asp

3.4. OBJECT & CLASSES IN JAVA References A class can be defined as a template or blue print that describes the behaviours of an object. An object is a set of states (attributes) and behaviours associated to it; an object is an instance of a class. A class is like a type of data, while the object is like a variable. If a variable is defined using the name of a class as its type, that variable has a reference to an object of that class. This means 57


the variable is not containing the actual object, but a reference to an object / class instance. When using the name of a class as a type, a reference to an object is created. These types are called reference types. There are two main characteristics of objects in Java: ďƒ˜ Objects are always dynamically allocated. The life of an object is linked to the program logic. It starts when the object is created and it ends when it is no longer in use. ďƒ˜ Objects are not contained by variables. A variable contains a reference to an object only. A variable reference may contain a reference to nothing. The value of such a variable is null. In Java it is not allowed for a reference type to be converted into a primitive type or viceversa. Objects In Java, objects are created by instantiation of a class, meaning the creation of an instance of a class. Declaration of the object is done by the syntax: NameClass nameObject;

Example: String s; Complex c; After declaration, the variable is initialized with a null value. Creation of the object is equivalent with the instantiation of a class and it is done using the keyword new and it is supposed to allocate the memory needed to keep the object. The address (reference) to that object will be memorized in the variable nameObject. nameObiect = new nameClass ();

Example: s=new String() ; Complex c=new Complex(2,3); Declaration and creation of the object can be done in the same command line.

58


Example: String s=new String() ; Complex c=new Complex(2,3); When the object is created its initialization is also done. The memory is not allocated when the object is declared, only with the use of keyword new! Referring the value of a variable is done by the syntax object.variable

Example: Complex c = new Complex(); c.re = 2; c.im = 3; System.out.println("Re=" +c.re+ " Im="+c.im); Accessing a method is done using the syntax object.method([parameters])

Example: Complex c = new Complex(); c.setRe(2); c.setIm(3); For more information go to http://www.w3schools.com/js/js_objects.asp Predefined objects and classes Many objects in JavaScript are predefined, have methods and properties, and can be used directly. Objects are hierarchically ordered, with the window object being at the top. The window object represents the current open window in a browser. On the next level there is the document object, which describes the content of the page. Then we have the form object. Besides the above three objects, there are a series of other predefined objects. 59


In order to use an object, this has to be created first, using the keyword “new” (see Java language). This way properties and methods of the objects can be called and used. Window object The window object represents the current open window of the browser, and it is used to get or change the properties of the window. There is also the option to create new windows. The window object is the topmost object in the JavaScript hierarchy. The main window of the web browser can be called using the reserved names „window” or „self”. Window Object Properties: PROPERTY closed defaultStatus innerHeight innerWidth locationBar menuBar name outerHeight outerWidth pageXOffset pageYOffset personalBar scrollBar statbar status toolbar

DESCRIPTION read read, write read, write read, write read read read, write read, write read, write read read read read read read, write read

Window Object Methods: METHOD DESCRIPTION alert(s) Displays an alert box with a message and an OK button blur() Turns the window inactive clearIntervall(p) Clears a timer set with setInterval() clearTimeout(p) Clears a timer set with setTimeout() close() Closes the current window confirm(s) Displays Stringul sas a dialog box with a message and an OK and a Cancel button moveBy(x,y) Moves a window relative to its current position with (x,y)-pixels 60


(horizontally (x) or vertically (y)). A negative value moves towards upper – left. moveTo(x,y) Moves a window to the specified (x, y – pixels) position open(p1,p2,p3) Opens a new browser window. p1: URL address of a file we want to open in the window. (an empty string returns an empty window) p2: name of the window p3: (optional) Visual properties of the window, separated by comma “,” prompt(p1,p2) Displays a dialog box that prompts the visitor for input. This has two buttons like for method confirm() and a field (text field), where the user can type text. p1 is a string which displays in the dialog box p2 is the text which first appears in the text field. resizeBy(x,y) Resizes the window by the specified pixels (x - to the right and y down). For negative values of x and y it makes the window smaller resizeTo(x,y) Resizes the window to the specified width (x) and height (y) in pixels scrollTo(x,y) Scrolls the document to the specified coordinates setIntervall(p1,p2) Calls a function or evaluates an expression at specified intervals (in milliseconds) until stopped with clearInterval() p1: function or code in JavaScript that has to be executed. p2: Time in milliseconds, until p1 is executed setTimeout(p1,p2) Calls a function or evaluates an expression after a timeout of specified number of milliseconds. p1: function or code in JavaScript that has to be executed. p2: Time in milliseconds, until p1 is executed Objects like document, event, history u. location. are directly derived from this object. For more information please go to http://www.w3schools.com/jsref/obj_window.asp Location object The location object contains information about the current URL. When a page is loaded (for example http://www.xyz.com/page.html) then location.href returns the address. For location.href we can define am address. The location object is part of the window object and is accessed through the window.location property. Document Object This object contains information about the content of a window in the browser. Document Objects Property:

61


PROPERTY alinkColor bgColor cookie fgColor lastModified linkColor referer title URL vlinkColor

DESCRIPTION A string that specifies the ALINK attribute. A string that specifies the BGCOLOR attribute. Specifies a cookie. A string that specifies the TEXT attribute. Returns the date and time the document was last modified A string that specifies the LINK attribute. A string that specifies the URL of the calling document. A string that specifies the contents of the <title> tag. A string that specifies the complete URL of a document. A string that specifies the visited link attribute.

Access read, write read, write read, write read, write read read, write read read read read, write

Document Objects Methods METHOD DESCRIPTION close() Closes an output stream and forces data to display. open() Opens a document for writing. The current document will be overwritten, and not a new window open! write(s) Writes string s in the current document writenln(s) Same as method write (), but starting on a new line The following objects are derived from the document object: all, anchors, applets, areas, embeds, forms, images, layers, links, plugins. Forms object This object is used to take user data as input for processing a form defined inside a HTML file. Can be accessed by three methods: 1. Using the form name- <form name=“FormNAME“> Access : document.FormNAME.reset() 2. Using the form index. First form is assigned index 0, etc. Access : document.forms[4].reset() 3. Using the form name as index indicator. The name is given by the attribute name from the <form> tag Access : document.forms[„FormNAME“].reset() PROPERTY action encoding

DESCRIPTION Presents the action attribute from <form> tag Presents the encoding type attribute from <form> tag 62

ACCES read, write read, write


length method name target

METHOD reset() submit()

Presents the number of elements on a form. Presents the method attribute in the <form> tag Presents the name attribute from the <form> tag Returns the name of the frame that becomes active when a form is submitted

read read, write read, write read, write

DESCRIPTION It deletes all data entered in a form. Simulates a mouse click on a reset button for the calling form, it has the same function as type=reset. Submits a form, it has the same function as the button that is introduced by type=submit

For more information please go to http://www.w3schools.com/js/js_validation.asp http://www.w3schools.com/js/js_validation_api.asp Image object This object is right below the document object in JavaScript hierarchy. It represents the properties of the HTML <img> element. The image object can be accessed two ways: 1. Using and index. The first image is assigned the index value 0. document.images[0].src 2. Using the name of the image in the <img> tag <img name=“BILD“ src=“t.jpg“> document.BILD.src PROPERTY DESCRIPTION Border Sets or returns the value of the border attribute of an image Complete Returns whether or not the browser is finished loading an image. True is the value returned for a completely loaded image. Height Sets or returns the value of the height attribute of an image Hspace Sets or returns the value of the hspace attribute of an image Length Returns the number of images Lowsrc Returns the value of low src as found in the <img> tag Name Returns the name value as found in the <img> tag Src Returns the complete path and name of the image as found in the src attribute Vspace Returns the value of the vertical distance relating to nearby objects width Returns the value of the width of the image 63

ACCES read read read read read read read read read read


Besides the method handleEvent(), which exists only in Netscape Navigator, the image object has other methods of its own. Date Object This object is used to displaydates and times. This object is created using the syntax: <script language=“JavaScript“> Function simpleDate() { Date1= new Date(); Date2= new Date(YYYY,MM,DD); Date3= new Date(“MM DD YYYY HH:mm:ss”); Date4= new Date(YYY,MM,DD,HH,mm,ss); } </script> For more information please go to http://www.w3schools.com/js/js_dates.asp http://www.w3schools.com/js/js_date_methods.asp Navigator object The navigator object contains information about the browser. It can be used to better adapt the script to each different browser. PROPERTY appCodeName appName appVersion language platform userAgent

DESCRIPTION Returns the code name (nickname) of the browser Returns the name of the browser Returns the version information of the browser Returns the language of the browser Returns for which platform the browser is compiled Returns the user-agent header sent by the browser to the server

ACCES read read read read read read

The navigator object, using the javaEnabled() method, specifies whether or not the browser has Java enabled, and if applets can be run. If Java is accepted, the returned value is true. For more information please go to http://www.w3schools.com/jsref/obj_navigator.asp 64


Layers object (all-) It is compatible only with Netscape. It contains the properties of the document object. The levels/layers are the marks of dynamic positioning of all elements in a page. It is under the document object in the objects’ hierarchy. The all object is only accessible in Explorer browser. This object contains properties and methods to create this concept: Calling the layers object: 1. Using index, characteristic to layers. The first level has index 0. document.layers[5].above 2. With reference to the layer’s name <layer name=“Layer0“> document. Layer0.above PROPERTY above background bgcolor below clip document left length name pageX pageY parentLayer src

top visibility

DESCRIPTION The layer above the current layer. The referenced layer background image. The referenced layer background color. The layer below the current layer. The referenced layer clipping region. Read only references to the document object that exists in the layer. The horizontal position of the layer relative to the containing layer or document is determined by this value. The number of the layer from HTML file The name of the layer. The layer X coordinates relative to the top level document. The layer Y coordinates relative to the top level document. The layer that contains the current layer. The URL the layer’s contents are from. This value is read/write. If this value is changed, the browser will load the contents of the URL in the layer. A read/write value that specifies the vertical position of the layer relative to the layer's containing layer. Determines if the layer is visible. This value can be read or written to. Possible values are: 65

ACCES read read, write read, write read, write read, write read, read, write read, read, write read, write read, write read, read, write

read, write read, write


Layer object methods: METHOD captureEvents() handleEvent() load(p1,p2)

moveAbove(p1) moveBelow(p1) moveBy(p1,p2) moveTo(p1,p2) releaseEvents() resizeBy(p1,p2) resizeTo(p1,p2) routeEvent()

DESCRIPTION This method instructs the window or document to capture all events of a particular type. See the event object for a list of event types. This method is used to call the handler for the specified event. This method is used to change the contents of a layer by loading a file containing HTML code into the layer.p1- is the file name p2-is the visible width of the layer in pixels Change the stacking order causing the current layer to appear on top of the target p1. Change the stacking order causing the current layer to appear below the target p1. Move the layer relative to its current location by p1 pixels to the left/right and p2 pixels up / down. Move the upper left corner of the layer to the absolute coordinates (p1, p2) specified relative to the top level document. Finishes the surveillance of events This method is used to resize the layer by the specified horizontal (p1) and vertical (p2) number of pixels. This method is used to resize a layer to the dimensions supplied with the width (p1) and height (p2) (both integers, in pixels) parameters. This method is used to send a captured event further down the normal event hierarchy

Properties and methods for all object Calling the object: 1. Using the tag name or identifier and an index pointer. For example: for tag <title>, the name is “title”. The index counts how many times the tag with this name is reference to. First tag has the index 0. If we have three titles defined with tag <h2>. To access the second tag we use the syntax: document.all.tags(„h2“)[1].innerText 2. Using the name given using the “name” attribute z.B : <h2 name=“Title2“>TITLE 2 </h2> document.all.Title2.innerText 66


PROPERTY className dataFld dataFormatrAs dataPageSize dataSrc id innerHTML innerText isTextEdit lang language length offsetHeight offsetLeft offsetParent offsetTop offsetWidth outerHTML outerText parentElement parentTextEdit recordNumber sourceIndex tagName title

DESCRIPTION Gets and sets the value of the class attribute of the specified element. Sets or retrieves a field of a given data source Sets or retrieves the format of a data source Sets or retrieves the number of data-pages which have to be returned simultaneously Reference to the object to which the connection was created Name of an element Content of a GHtml type element Text content of a GHtml type element Returns true-if the element is editable, false if not Returns the language of the element as long as it was defined by attribute lang. Returns the script language The number of HTML tags in a file. Height of the element in pixels. Space in pixels from the element to the left margin of the window. Reference to the parent object. Space in pixels from the element to the top margin of the window. Width of the element in pixels Returns the content of a HTML tag, including the start and end tags Text content of a HTML tag, including the start and end tags Parent element of the current element. Returns the next editable element. Retrieves the ordinal record from the data set that generated the object. Retrieves the ordinal position of the object, in source order, as the object appears in the document's all collection. Returns the name of a tag Returns the content of the title

67

ACCES read, write read, write read, write read, write read, write read, read, write read, write read, read, write read, read, read, read read, read, read read, write read, write read, read, read, read, read, read, write


METHOD

DESCRIPTION Click() This method can be used to execute a click on an element as if the user manually clicked on it. Contains(p1) Returns true if and only if the element contains another element with the value (p1). getAttribute(p1,p2) Returns the value of the attribute p1 of an element or an empty string. P2 returns true if case sensitive. insertAdjacentHTML(p1,p2) Parses the specified text p2 as HTML or XML text and inserts it at the location p1. Possible values: BeforBegin, AfterBegin, BeforEnd, AfterEnd. insertAdjacentText(p1,p2) Same as insert AjacentHTML, but inserts plain text only. removeAttribute(p1,p2) Removes the specified attribute from an element in a HTML tag. p1-the name of the attribute in the tag. p2 is true if this is case sensitive. scrollIntoView(p1) Scrolls the current element into the visible area of the browser window. p1=true-if the element has to appear in the top part of the window. p1=false-if the element has to appear in the bottom part of the window. setAttribute(p1,p2,p3) Adds the specified attribute to an element, and gives it the specified value. If the specified attribute already exists, only the value is set/changed. p1-the name of the attribute. p2-the value of the attribute. p3-true-if it is case sensitive. Math Object It allows you to perform mathematical tasks on numbers. It includes several mathematical methods and constants. Constants: PI (number pi=3,14..) Euler’s number (e=2,71..). Methods:  abs(x) – absolute value of x  cos(x) – cosine of x (x is in radians)  tan(x) – tangent of x  sin(x) – sine of x (x is in radians)  acos(x) – arccosine of x, in radians  asin(x) – arcsine of x, in radians  atan(x) – returns the arctangent of x as a numeric value between -PI/2 and PI/2 radians  floor(x) –rounds a number down to the nearest integer to x. Example: Math.floor(-3,73), returns -4.  random(x) –a random number in the interval [0,1] 68


    

round(x) – rounds a number to the nearest integer x sqrt(x) –square root of x pow(x,y) – returns the value of x to the power of y log(x) – returns the natural logarithm (base E) of x exp(x) – returns the value of Ex

Example: Math.floor(1+100*Math.random()); will return a random number between [1 and 101]. For more information please go to http://www.w3schools.com/js/js_math.asp Obiectul Array In JavaScript we can only create arrays. Arrays are of the object type. An array is declared with Array() and its elements are accessed using name[index]; Functions and methods of Array:  length property;  sort()method sorts an array alphabetically;  reverse()method reverses the elements in an array;

Example: vv=new Array(4); vv[2]=6; alert(vv[2]); Creating a matrix of 4 lines and 3 columns is done like this: vv=new Array(4); for (i=0;i<4;i++) vv[i]=new Array(3); Each element of the matrix is an array. For more information please go tohttp://www.w3schools.com/js/js_array_methods.asp String Object

 

String methods help you to work and manipulate strings. Creation of a sting can be done in two ways: using the keyword new: var a = new String (“JohnDoe”) ; assigning to a variable the string: a = “JohnDoe”; The length property returns the length of a string.

Methods. Some of its methods are:  search(s) – this method searches a string s for a specified value and returns the position of the match. If not found it returns -1. 69


charAt(index) – returns the char at index position;  slice (i1, i2) – extracts a part of a string and returns the extracted part in a new string.  substr(i1,l) –it returns the string starting at i1 and with a length l;  toUpperCase () – A string is converted to upper case;  toLowerCase() - A string is converted to lower case;  replace(word 1, word2) –replaces a specified value word1 with another value word2 in a string;  bold() – A string is converted to bold case;  italics() - A string is converted to italics case;  fontcolor(“name_color”) – A string is converted to color “name_color”  fontsize(“size”) - A string is converted to fontsize“size”  link(“adr_http”) – creates a hyperlink to adr_http For more information please go to http://www.w3schools.com/js/js_string_methods.asp 

Animation By displaying more images at the same position, each image being displayed for a certain amount of time, we can create an animation. There are certain predefined functions for dealing with this. For more information please go to http://www.w3schools.com/js/js_objects.asp setTimeout method Syntax: setTimeout(function, milliseconds) It executes a function, after waiting a specified number of milliseconds. The first parameter is a function to be executed. The second parameter indicates the number of milliseconds before execution. clearTimeout method Syntax: clearTimeout(timeoutVariable) The clearTimeout() method uses the variable returned from setTimeout(): If the function has not already been executed, you can stop the execution by calling the clearTimeout() method. For more information please go tohttp://www.w3schools.com/js/js_function_definition.asp Classes Class declaration [public][abstract][final] class NameClass 70


[extends NameSuperclass] [implements Interface1 [, Interface2 ... ]] { //class body } Class header: [public][abstract][final] class NmeClass is made of class modifiers, the reserved keyword class and the class name NameClass. Use of brackets [] indicates that is between them is optional. Class modifiers are:  public: this modifier declares that the class can be used by objects outside the current package. By default a class can only be used by other classes in the same package in which it is declared (if no package is specified, all classes in the current folder are considered to be in the same package). The system variable CLASSPATH defines the search space. By convention, when you use the public keyword in a class declaration, you should make it the very first item in the declaration.  abstract: this modifier declares that your class is an abstract class. Meaning it is a template class, used only to create a common model for a series of subclasses. An abstract class may contain abstract methods (methods with no implementation). Abstract classes are intended to be sub-classed and cannot be instantiated.  final class can only be declared when it is completely defined. That is, that your class cannot be sub-classed. There are (at least) two reasons why you might want to do this: security reasons and design reasons. The body of a class comes after the header and it is always between accolades. It contains two different sections:  variable declarations;  method declarations. A class's member variables represent a class's state and its methods implement the class's behaviour. Within the class body you define all the member variables and methods supported by your class. Variables and methods of a class can bear the same name. Member variables Typically, you declare a class's member variables first and then you provide the method declarations and implementations, although this is not required. class NameClass { //variable declaration //methods declaration } 71


Variables of a class are only those declared in the body of that class and not in the body of a method. The variables declared in a method are local variables to that method. A member variable declaration defines the following aspects of the variable:  the name of the variable;  data type;  level of access to the variable from other classes;  if it is a constant or not;  the type of the variable: instance of class The syntax of variable declaration is: [modifiers] typeofdata nameVariable [ = initialvalue] ; Where the modifier can be:  an access specification: public, protected, private;  a reserved keyword: static, final, transient, volatile.

Example: double x; protected static int n; public String s = "abcd"; private Point p = new Point(10, 10); final long MAX = 100000L; Methods Definition Methods are used to describe the behaviour of an object. The declaration of a method is done like so: [modifiers] returnType methodName ([arguments]) [throws exceptionType] { //method body } Method modifiers A modifier can be:  an access specification: public, protected, private;  a reserved keyword: static, abstract, final, native, synchronized.  abstract is used to define abstract methods. An abstract method is a method without implementation which belongs to an abstract class. 72


 

final is used when that method cannot be super-defined in the subclasses of the class in which it is defined as final. This is useful when the respective method has an implementation which doesn’t need to be changed in its subclasses. native is used to reuse functions written in another programming language (C for instance). synchronized is used when multiple execution threads are run, and that method is used to share a common resource. It is basically a stop which allows the method to be executed at a particular moment on only one execution thread.

Returning a Value from a Method Methods can return or not a value (an object) at their end. The type of the returned value can be of primitive data type (int, double, etc.) as well as a reference to an object of a classIf a method does not return a value, it must be declared to return void.

Example:voiddisplayResult () Methods use the return operator to return a value. Method arguments When you write your method, you declare the number and type of the arguments required by that method. You declare the type and name for each argument in the method signature and the set of arguments to any method is a comma-delimited. methodName ([type1 argument1], [type2 argument2] ... ) In Java, you can pass an argument of any valid Java data type into a method. This includes primitive data types such as doubles, floats and integers, or reference data types such as objects and arrays.

Example: voidaddPerson (String name, int age, float income){ ... } whereString is a reference data type and int and float are primitive data types. In Java a method cannot have a variable number of arguments. This means that calling a method has to be done with the specification of the exact number and types of arguments. It is not allowed to group arguments by their type. 73


Class constructors The constructors for a class are special methods which possess the same name as the class, do not return any value and are used to initialize the objects of the respective class at the moment of their instancing. The constructors control the way in which an object is created and initialized. class Complex { Complex() { //constructor } } A class can have one or several constructors which should be different according to the list of received parameters. Thus different types of initializations of the objects are allowed when creating the object, according to the number of parameters used to invoke the constructor. Inheritance The Principle of inheritance The inheritance is useful as it reduces the re-writing of the code. A class can be inherited by another class (all the characteristics of the former class will be found in the latter class). The new class can change some of its behaviour, maybe add something new or ignore uninteresting items.In Java, in order to create a new class one must specify: the inherited class and the differences from the inherited class. The inherited class is specified in extends clause. modifier ClassName extends BasicClass The class inherits all the accessible methods and the variables of its super class.

Example: The following class hierarchy A is expressed in Java as follows: class A{ ... } B class B extends A{ ... } class C extends B{ C D ... } class D extends B{ ... } Note: In Java multiple inheritances is not allowed. A class cannot inherit more than one class. 74


Interfaces A Java interface defines a set of methods but does not specify any implementation for them. A class which implements an interface must define all the methods of the interface. Consequently, an interface is a collection of methods without implementation and declaration of constant variable. Defining an interface can be performed with the use of the keyword interface: [public] interface NameInterface extends SuperInterface1 [,extends SuperInterface2...]] { //body of interface: constants and abstract methods } An interface can only be declared publicly. A class can extend unlimited interfaces. These are called superinterfaces and are separated by commas. The body of an interface contains:  constants: they can be either declared or not with the modifiers which are implicitly public, static and final; no other modifier can appear in the declaration of an interface variable. The constants in an interface must be initialized. The implementation of an interface is performed through the keyword implements: class ClassName implements InterfaceName or class ClassName implements Interface1, Interface2... A class can implement a multitude of interfaces. A class which implements an interface must define all the interface methods. Packages A package is a collection of related classes and interfaces. They are employed to find and use classes more easily, in order to avoid name conflicts and to control the access to certain classes. In Java all the classes and interfaces are grouped into different packages according to their functionality. The most important packages provided by Java are:  The java.lang package includes the basic classes of the language;  The java.io package consists of the classes for system input/output, and file use;  The java.math package includes the classes in which mathematical operations are defined;  The java.util package includes useful classes: Vector, Stack, Random, Date etc;  The java.text package provides support for text formatting;  The java.sql package offers support for SQL interrogations;  The java.beans package includes the classes necessary for writing recyclable components;  The java.net package consists of the classes which ensure network access; 75


 The java.awt package includes the graphics classes (Abstract Windowing Toolkit);  The javax.swing package includes the graphics classes; it extends the functionality of the classes in the java.awt package.  The java.rmi package consists of the classes which ensure remote execution (Remote Message Interface);  The java.securitz package includes the classes which provide security mechanisms: encryption, authentication; To use the component of a package, the current class must be presented with the package in which the component can be found or only the component. This can be performed by importing the package or solely the class. Importing a package, a class or an interface The import can be performed with the help of the import instruction. The package import is done by specifying the name of the package followed by the '*'symbol. '*' shows that all the classes and interfaces of the package have been imported. import PackageName.*;

Example: import java.io.*; import javax.swing.*; Once the import of the package has been performed in a file, any class within the package can be accessed through its name.

Example: Data Class belongs to the java.util. package import java.util.*; public class ExData{ public static void main(String[] args) { Date d=new Date(2003,4,13); System.out.println(d); } } One can import classes (interfaces) by specifying the name of the class (interface) in a package we want to use: import PackageName.ClassName; 76


Creating a package A directory is created under the name packageName, in which we save all the source files containing the classes and the interfaces which we want to group in a package. The name of the directory will become the name of the package. On the first line of each file in the PackageName directory it is specified that all the classes in the respective file will belong to the class. This is performed by: package PackageName; Consequently, the class code added to a package is presented as follows: package PackageName; public class ClassName{ ... } The package instruction exerts action on the entire source file at the beginning of which it appears. In other words, we cannot specify that certain classes in a source file belong to one package and other classes to another.

3.4. INPUT STREAMS AND OUTPUT STREAMS The data can be collected from any source (file, disk, network, memory, another program) and it can be of any type (objects, characters, images, sounds). To bring data, a Java program opens a stream (communication channel) for a data source and reads the data. A stream which reads data is called input stream.

Similarly, a program can send data to an external destination by opening a stream (communication channel) directed towards the destination and writing the respective data in series. A stream which writes data is called output stream.

The reading algorithm is: 77


open stream > as long as there is data >read data >close stream The display algorithm is: open stream > as long as there is data >write data >close stream The java.io package provides a collection of classes used for reading and display. Consequently, any program which requires input/output operations must import the java.io package: import java.io.*. Classification of streams There are three types of stream classifications:  According to the “direction” of the open communication channel, streams are divided into: o input streams (for reading data) o output streams (for writing data)  According to the type of data they operate on: o octet streams (serial communication is performed on 8 bytes) o character streams (serial communication is performed on 16 bytes)  According to their action: o reading streams/ writing streams o processing streams Class hierarchy for working with streams Character streams The root classes for the class hierarchy which manage the character streams are Reader (for input streams) and Writer (for output streams). The class hierarchy for input character streams is:

78


The class hierarchy for output character streams is:

Octet streams The root classes for class hierarchy which manage the octet streams are InputStream (for input streams) and OutputStream (for output streams). Their subclasses are used for reading and writing binary data such as images and sounds. The class hierarchy for octet input streams is:

The class hierarchy for octet output streams is:

79


Input/output superclassses The Reader and InputStream classes define similar methods for reading data, while the type of parameters differs. TheReader Class int read() int read(char cbuf[ ]) int read(char cbuf[ ], int index, int length) The InputStream Class int read() int read(byte cbuf[ ]) int read(byte cbuf[ ], int index, int length) Similarly, the Writer and OutputStream classes define similar methods for displaying data, while the type of parameters differs. TheWriter Class int write() int write(char cbuf[ ]) int write(char cbuf[ ], int index, int length) The OutputStream Class int write() int write(byte cbuf[ ]) int write(byte cbuf[ ], int index, int length) Creating a stream Any stream is an object of the class which implements the respective stream. Creating a stream is similar with creating objects, using the instruction new().

Example: //creating a character input stream FileReader in = new FileReader("file_input.txt"); //creating a character output stream FileWriter out = new FileWriter("file_output.txt"); // creating an octet input stream FileInputStream in = new FileInputStream("file_input.txt"); //creating an octet output stream FileOutputStream out = new FileOutputStream("file_output.txt"); 80


Consequently, creating a stream which write/reads data from an external device will display the general: PrimitiveStream Stream name = new PrimitiveStream (external device) Reading keyboard data The System.in object Generally, the keyboard represents the standard external input device. The System class contains a member variable which represents the keyboard or the standard input stream. This variable is called in and it is an instance of the InputStream class.

Example: Characters are read from the keyboard. Each read character is added to a string of characters. The reading is complete when the Enter key is pressed. 1. class Reading1 { 2. public static void main(String args[]) { 3. StringBuffer s=new StringBuffer(); 4. char c; 5. try { 6. while((c=(char)System.in.read()) != ’\n’) 7. s.append(c); 8. } 9. catch(Exception e) { 10. System.out.println(”Error:”+e.getMessage()); 11. } 12. System.out.println("Sirul este:"+s); 13. } 14. } The InputStreamReader Class It reads octets and turns them into characters. Turning octets into characters is performed according to a codification rule. If no such rule is specified, then default encoding is used (provided by the system property “file encoding”). The InputStreamReader class has the following constructors: InputStreamReader(InputStream in) InputStreamReader(InputStream in, String enc) The main method for reading a character is: int read() 81


Example: Characters are read from the keyboard. Each read character is added to a string of characters. The reading is complete when the Enter key is pressed. 1. import java.io.*; 2. class Reading3 { 3. public static void main(String args[]) { 4. InputStreamReader in= 5. new InputStreamReader(System.in); 6. char c; 7. StringBuffer s=new StringBuffer(); 8. try { 9. while((c=(char)in.read()) != ’\n’) 10. s.append(c); 11. } 12. catch(Exception e) { 13. System.out.println(”Error:”+e.getMessage()); 14. } 15. System.out.println(s); 16. } 17. } The BufferedReader Class If the InputStreamReader class is used, the reading will be performed character by character (in other words, the disk is accessed every time). The BufferedReader Class has the read() method defined by the same signature as the one defined in the InputStreamReader, but it also defines the readLine() method. This method can be used to read a string of characters ended in ’\n’,’\r’ sau ’\r\n’.

Example:A string of characters is introduced with the keyboard. By pressing the Enter key, the string is read entirely and deposited in a String. 1. import java.io.*; 2. class Reader4 { 3. public static void main(String args[]) { 4. InputStreamReader in1= 5. new InputStreamReader(System.in); 6. String s=new String(); 82


7. 8. 9. 10. 11. 12. 13. 14. 15. 16.

try { BufferedReader in= new BufferedReader(in1); s=in.readLine(); } catch(Exception e) { System.out.println(”Error:”+e.getMessage()); } System.out.println(s); } }

Reading and writing data in a file The FileReader and FileWriter Classes The FileReader class is used to read data in a text file. Its most important constructors are:  it creates a stream which reads characters in the name file public FileReader(String name) throws FileNotFoundException  it creates a stream which reads characters in the varFis file. public FileReader(File varFis) throws FileNotFoundException The FileWriter class is used to write data in a text file. Its most important constructors are:  it creates a stream which writes characters in the name file public FileWriter (String name) throws IOException  it creates a stream which writes characters in the varFis file public FileWriter (File varFis) throws IOException

3.5. APPLETS What is an applet? An applet represents a display area (container) which can be included in a Web page and managed through a Java program. This type of program is also called mini-application

83


The code of an applet can be made of one or several classes. One of these is the main class and it extends the JApplet class, being the class which must be specified in the HTML document that describes the Web page in which we want to include the applet. The main difference between an applet and an application resides in the fact that an applet cannot be executed independently, but it is executed by the browser in which the Web page containing the applet is uploaded. An interesting application is executed by invoking the java interpreter, having a parameter with the name of the main class of the application, the main class being the one which contains the main method. An applet cannot approach the local hard disk for reading or writing. The package which offers support for creating applets is javax.swing. The JApplet class provides everything necessary for building and maintaining an applet. Creating an applet involves implementing the methods provided by the JApplet class which helps us describe the desirable behaviour of the applet. The class hierarchy is: java.lang.Object | +--java.awt.Component | +--java.awt.Container | +--java.awt.Panel | +--java.applet.Applet | +--javax.swing.JApplet The functions of an applet The execution of an applet starts at the moment when a browser displays a web page in which the respective applet is included and can consist of several stages. Each stage is closely connected to an event generated by the browser and determines the invoking of a specific method from the class which implements the applet.  Loading in the memory – an instance of the main class of the applet is created and loaded in the memory.  Initialization – the init method is invoked which allows the initialization of various variables, reading the input parameters, etc. The init method is also responsible for organizing all the components according to shape.  Start – the start method is invoked

84


 Effective execution – consists in the interaction between the user and the components displayed on the area of the applet.  Temporary stop – In case the user leaves the Web page in which the applet is running, the stop method is invoked, providing the possibility to temporarily stop as long as it is not visible in order not to waste the processor time. The same happens if the browser window is minimized. When the web page containing the applet becomes active again, the start method will be invoked.  Definitive stop – When all the instances of the browser used for visualizing are closed, the applet will be erased from the memory and the destroy method will be invoked, to allow the release of the contained resources. The invoking of the destroy method is always preceded by invoking stop. The general structure of an applet import javax.swing.JApplet; import java.awt.*; import java.awt.event.*; public class AppletStructure extends JApplet { public voidinit() { /* the code describes the actions we want to perform by starting the class of the applet */ } public voidstart() { /* the code describes the actions we want to perform by launching the applet in execution or returning to the applet page */ } public void paint(Graphics g) { /* the code describes the actions we want to perform by each redrawing of the applet window */ } public voidstop() { /* the code describes the actions we want to perform when the applet stops temporarily (the Web page is no longer visible, the browser window is minimized, etc) */ } public voiddestroy() { /* The code describes the actions we want to perform when the applet is destroyed (the browser leaves the .html document from which the applet was invoked) */ } } 85


Note: These methods are automatically invoked by the browser and need not be explicitly invoked from the program! HTML A Web browser interprets the content (text) of an .html file (Hyper Text Markup Language). The HTML language consists in a series of mark-ups (tags). Tags are used to describe the way in which the text will be displayed, to tell the browser to use additional Internet resources, contained in different files. The syntax of a tag is: <TagName [parametre ]> text </TagName> The parameters are written as follows: ParametreName = value The structure of a .html document is: <HTML> <HEAD> <TITLE> document title </TITLE> </HEAD> <BODY> ... <APPLET parametres> <PARAM parametres> <PARAM parametres> ... <PARAM parametres> </APPLET> ... </BODY> </HTML> We consider the basic notions of HTML familiar to the reader. What is of interest in order to create applets is the <APPLET> tag. This tag has mandatory and optional parameters. Mandatory parameters: ďƒ˜ CODE – its value represents the name of the file which contains the class of the applet: ClassName.class;

86


 WIDTH – its value is the width of the window attributed by the browser to the applet in order to display the .html document;  HEIGHT – its value is the height of the window attributed by the browser to the applet to display the .html document; Optional parameters:  CODEBASE – its value is the URL address (Universal Resource Locator) or the path to the file containing the class of the applet. If a parameter is absent, the class will be searched in the current directory (from which the .html file was loaded);  VSPACE – its value is the height of the area (in pixels) which will be left white on top and bottom of the applet window;  HSPACE – its value is the width of the area (in pixels) which will be left white on the left and right side of the applet window;  ALT – Specifies the text which must be displayed if the browser understands the <APPLET> tag but cannot run Java applets.  NAME – Provides the opportunity to assign a name for the respective instance of the applet, so that several applets on the same page could communicate with each other using their names.  ALIGN – Specifies the alignment options of the applet within the Web page. This attribute can be assigned one of the following values: left, right, top, texttop, middle, absmiddle, baseline, bottom, absbottom, their significance being the same as in the IMG tag. The <PARAM> tag is not mandatory and can appear when the user expects the applet to receive the parameters. A parameter is defined by:  NAME – represents the name of the variable recognized by the applet;  VALUE – represents the value received by the applet; it is the String type. For additional information go to:http://www.w3schools.com/js/default.asp

3.6. GRAPHICAL INTERFACES What is a graphical interface?A graphical interface refers to all types of visual communication between a program and its users. The graphical interface does not only refer to what the user sees on the screen but also to all the communication mechanisms between the user and the program. The Java language provides a large number of classes to implement the different functions of the graphical interface, but we will further present those who allow the development of a graphical user interface (GUI – Graphical User Interface). In general, the development of a graphical application requires the following steps: 1. creating a display area (such as a window) to place the graphical objects on in order to communicate with the user (buttons, edit boxes, texts, etc); 87


2. creating and placing the graphical objects on the display area in the right positions; 3. defining certain actions which should be performed when the user interacts with the graphical objects of the application; 4. "listening to" the events generated by the objects at the moment of interaction with the user and performing the actions as they had been defined; In Java there are two packages of classes which offer graphical services: java.awt and javax.swing. In this course we will present the Swing package which is an extension of the awt. package. “Swing” was the code name assigned to the project which developed new components. Starting with javax.swing is the name of the packages for Swing API. The majority of graphical objects are subclasses of the JComponent class, which defines generically a graphical component that can interact with the user. Thus, a graphical component is any object which possesses a graphical representation that can be displayed on the screen and interact with the user. Examples of components are windows, buttons, scrollbars, etc. In general, all the components are defined by appropriate classes which can be found in the javax.swing package, the JComponent class being the abstract superclass of all these classes. Creating graphical objects doesn’t automatically display them on the screen. First they must be placed on a display area which can be a window or the surface of an applet, and will become visible at the moment when the display area becomes visible. This area, on which the graphical objects are placed, represents the instance of a class obtained through the extension of the Container class; for this reason the display surfaces will also be called containers. The Container class is a distinctive subclass of the Component class, being the super class of all the Java display areas (windows, applets, etc). The Swing package provides the programs which use its components and the possibility to choose the type of interface (“look and feel”) or, merely, to preserve the one characteristic of the respective platform. Main containers An independent application needs its own windows to display the graphical components. This type of display on which the graphical objects are placed is called display area or container and represents an instance of a class obtained through the extension of the Container superclass. The most important main containers are: JFrame, JDialog, JWindow and JApplet. The class hierarchy is:

88


java.awt.Container |__ java.awt.Panel |__ java.applet.Applet |__ javax.swing.JApplet |__ java.awt.Window |__ java.awt.Frame | |__ javax.swing.JFrame |__ java.awt.Dialog | |__ javax.swing.JDialog |__ javax.swing.JWindow The JFrame Class The JFrameClass is used to implement the main windows. This component has certain features such as the frame, the title bar and the controls of the window provided by the operating system. This cannot be altered. The behaviour of the windows (resizing, minimizing, positioning) is controlled by the operating system. The constructors of the JFrame class are: JFrame() – creates a window without title, invisible at first. JFrame(String title) – creates a window with specified title, invisible at first. So a newly created window is invisible. In order to make it visible the show () method is invoked.

Example: A window is created and displayed with the title “First window”. import javax.swing.*; public class AplJFrame { public static void main(String args[]) { JFrame f = new JFrame("First window"); f.show(); } } The pack() method is used to apply a size to the frame. An alternative for the pack () is to explicitly set the size of the frame by invoking the setSize () method. In general, it is recommended to use the pack () method instead of the setSize () method, as the pack () method leaves the calculation of the frame size to the layout manager which also considers other factors that can affect the size of the components. The setVisible() method is used to display the frame. 89


The getContentPane() method returns the contentPane object of the frame. Any component is added to the contentPane of the current frame.

Example: import javax.swing.*; import java.awt.*; import java.awt.event.*; public class AplicFrame{ public static void main(String[] args) { try { UIManager.setLookAndFeel( UIManager.getLookAndFeel()); } catch (Exception e) { } /*The main container is created (from the top of the hierarchy) and the components are added on it*/ JFrame frame = new JFrame(); JLabel comp = new JLabel("label1"); JLabel comp1 = new JLabel("label2"); //label2 will be placed over label1 frame.getContentPane().add(comp); frame.getContentPane().add(comp1); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); frame.pack(); frame.setVisible(true); } }

90


Secondary windows and the JDialog class To create secondary windows the JDialog is usually employed. Other secondary windows can be created with: JOptionPane – creates a standard dialogue window ProgressMonitor – creates a window which shows the progress of an operation JColorChooser – creates a window for the selection of colour JFileChooser – creates a window for the selection of a file Every secondary window is dependent on a main window (a frame). A dialogue window can be modal. If it is modal, it blocks the access to any other window in the program. The JWindow class The JWindow class is used to implement complete windows (completely white rectangles). These windows do not contain a title bar or window controls. The JApplet class The JApplet class is used to implement applets. The shape of the main containers is illustrated in the following picture:

Intermediate containers JFC components used to organize windows. The intermediate containers are used to divide the window in several sections or to group the components. Swing provides the following intermediate components: Panel – It is the most flexible and frequently used intermediate container. It can be implemented using the JPanel class. A panel groups the components in a window or another panel. A panel can use any layout or layout manager and can have a border (border). 91


Scroll Pane Split Pane Tabbed Pane Tool Bar

– Provides the scroll bar (horizontal and vertical) for oversized components. – Displays two components in a specified space, offering the user the possibility to resize every component. – Contains several components but only displays one at a time. The user can choose between the components. – Groups the components (buttons, in general) in a row or column, enabling the user to move it anywhere.

Using the layout managers (Layout Manager) A program can have different interfaces, even though the same components are used. This is due to the use of different layout managers which control the size and location of the components. The layout management is the process which determines the size and location of the components. Implicitly, each container possesses a layout manager - an object which manages the location of each component on the container. This object implements the Layout Manager interface. This can be replaced with another to meet the requirements. Generally, the layout manager is set for two types of containers: contentpanel (implicitly uses BorderLayout) and JPanel (implicitly uses FlowLayout). Every time a component is added to the container one must consider the layout manager of the respective container. Setting the layout manager To change the layout manager used by a container the setLayout method is invoked. The method can receive as parameter any instance of a class which implements the LayoutManager interface. The sequence of attaching a manager to a container is: FlowLayout manager = new FlowLayout(); container.setLayout(manager); or: container.setLayout(new FlowLayout());

For example: JPanel jp = new JPanel(); jp.setLayout(new BorderLayout()); If the argument is null, the container doesn’t use a layout manager. In this case the size and location of every component on the container must be specified.

92


The most widely used managers in Java are: BorderLayout, BoxLayout, FlowLayout, GridBagLayout and GridLayout. BorderLayout is the implicit layout manager for each main container. A BorderLayout has five areas in which the components can be positioned: north, south, east, west and center. The BoxLayout manager lays the components on a single row or column. It complies with the minimum sizes of the components and allows for their alignment. The CardLayout class enables the implementation of an area which contains different components at different times. The tabbed panes are intermediate containers which provide a similar functionality. A CardLayout is generally controlled by a Combo Box, its state determining the panel to be displayed. FlowLayout is the implicit layout manager for any JPanel. It arranges the components from left to right, from top to bottom. GridLayout arranges the components in the cells of a table. Each component fills all the available space in a cell. All the cells are the same size. By resizing the GridLayout window, the cells will change their sizes so that they fill all the space in the window. The GridLayout class has two constructors: public GridLayout(int rows, int columns) public GridLayout(int rows, int columns, int horizontalGap, int verticalGap) At least one of the two arguments rows and columns must not be null. The horizontalGap and verticalGap arguments in the second constructor allow the specifying of the number of pixels between the cells. Their value is implicitly 0. The GridBagLayout is the most sophisticated and flexible layout manager provided by the Java platform. It arranges the components into the cells of a table, each component being able to fill several cells. The rows/columns of the grid needn’t be same height/width. For each component added to the window a series of restrictions are set by creating an object of the GridBagConstraints class. The same instance of the GridBagConstraints can be used for several components, even though they have different restrictions. The GridBagLayout extracts the values of the restrictions and doesn’t use the GridBagConstraints. The class contains the following attributes which can be set: gridx, gridy – Specifies the row and column at the upper left of the component. The leftmost column has address gridx=0 and the top row has address gridy=0 gridwidth, gridheight – Represents the number of columns (for gridwidth) or rows (for gridheight) on which the component will be displayed. The default value is 1. fill – Is used when the component display area is larger than the required size, in order to determine how the component can be resized. The valid values are:  NONE (default), 93


HORIZONTAL (maximizes the component horizontally so that it fills the entire available area without changing the height),  VERTICAL (maximizes the component vertically so that it fills the entire available area without changing the width),  BOTH (maximizes the component so that it fills the entire available area). ipadx, ipady – Used to resize the cells. It specifies the value added to the minimum size of the component. The default value is 0. The width/height will have the minimum value plus ipadx*2 / ipady*2 pixels (it applies to both edges of the component). insets – Specifies the distance between the component and the edges of the area it is displayed on. The attributed value is an Insets object. anchor – Is used when the component is smaller than the area it will be displayed on, to determine where to place the component. Valid values are CENTER (default), NORTH, NORTHEAST, EAST, SOUTHEAST, SOUTH, SOUTHWEST, WEST and NORTHWEST. weightx, weighty – Are used to determine how to distribute space among the columns/rows. If no value is specified (0 is default), then all the components will be grouped in the center of the container as GridBagLayout places any extra space between its grid of cells and the edges of the container. 

Managing events Pressing a key or mouse button of the mouse will generate an event. In order to manage the event an object is necessary to implement the appropriate interface and be recorded as an event consumer (event listener). Swing components can generate several types of events. Some of the corresponding interfaces are: ActionListener actions over a control (click on a button, Enter after inserting a text in a field, selection in a menu) ComponentListener resizing, moving or hiding a component FocusListener gaining/losing the focus ItemListener selecting/ deselecting an object in the list, menu, etc. TextListener changing the text in the control AdjustmentListener changing a value extended between two limits (eg: Scrollbar) KeyListener pressing a key MouseListener pressing the mouse button while the cursor is on the respective component MouseMotionListener drag; moving the mouse along a component WindowListener closing, minimizing, maximizing etc. ContainerListener adding, deleting a component ListSelectionListener changing the selection in a table or list 94


Every event is represented by an object which offers information on the event and identifies the source of the event. Each event generator can have several listeners. event listener event generator

event object

event listener event listener

Once occurred, an event is distributed to all the registered listeners (it is not consumed merely by the first one). As stated earlier, in order for the events of a component to be intercepted by an instance of a class listener, this class must be registered in the list of the listeners of the respective component. I stated list as the events of a component that can be listened to by a multitude of classes on the condition that these are registered in the respective component. Registering a class in the list of component listeners is performed with the help of methods in the Component class type addXXXListener, and deleting it from the list can be performed with removeXXXListener, whereXXX represents the type of event.

Example of managing an event The following steps are necessary: 1. The class has to implement the appropriate interface or to extend a class which implements the interface public class ClassName implements ActionListener {...} 2. Writing the code which registers an instance of a class (which will listen to the event) as listener for one or several of the components. Component.addActionListener(instanceClassName); 3. Writing the code which implements the methods in the listener interface. public void actionPerformed(ActionEvent e) { //code which reacts to action }

95


Example: import javax.swing.*; import java.awt.*; import java.awt.event.*; public class AplicEv extends JFrame{ JButton uB,lB,rB; JPanel pbut; JTextField txt; Listener lsn; TextWorker txtWorker; public AplicEv() { uB=new JButton("UpperCase"); lB=new JButton("LowerCase"); rB=new JButton("Delete"); uB.setActionCommand("ActUpperCase"); lB.setActionCommand("ActLowerCase"); pbut=new JPanel(); pbut.add(uB); pbut.add(lB); pbut.add(rB); txt= new JTextField("Insert text!"); lsn=new Listener(); getContentPane().setLayout(new BorderLayout()); getContentPane().add("North",txt); getContentPane().add("Center",lsn); getContentPane().add("South",pbut); txtWorker=new TextWorker(txt); rB.addActionListener(lsn); uB.addActionListener(lsn); lB.addActionListener(lsn); rB.addActionListener(txtWorker); uB.addActionListener(txtWorker); lB.addActionListener(txtWorker); } public static void main(String[] args) { 96


AplicEv f=new AplicEv(); f.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); f.addWindowListener(f.lsn); f.setSize(400, 125); //f.pack(); f.setVisible(true); } } class TextWorker implements ActionListener { private JTextField txt; public TextWorker(JTextField txt){ this.txt=txt; } public void actionPerformed(ActionEvent e){ String c=e.getActionCommand(); if(c.equals("Delete")) txt.setText(""); if(c.equals("ActUpperCase")){ String oldText=txt.getText(); String uText=oldText.toUpperCase(); txt.setText(uText); } if(c.equals("ActLowerCase")){ String oldText=txt.getText(); String lText=oldText.toLowerCase(); txt.setText(lText); } } } class Listener extends JTextArea implements ActionListener, WindowListener{ public Listener(){ super(); this.setEditable(false); 97


} public void actionPerformed(ActionEvent e){ append(e.paramString()+" [ "+e.toString()+" ]\n"); } public void windowClosed(WindowEvent e){ append(e.paramString()+" [ "+e.toString()+" ]\n"); } public void windowOpened(WindowEvent e){ append(e.paramString()+" [ "+e.toString()+" ]\n"); } public void windowClosing(WindowEvent e){ append(e.paramString()+" [ "+e.toString()+" ]\n"); } public void windowIconified(WindowEvent e){ append(e.paramString()+" [ "+e.toString()+" ]\n"); } public void windowDeiconified(WindowEvent e){ append(e.paramString()+" [ "+e.toString()+" ]\n"); } public void windowActivated(WindowEvent e){ append(e.paramString()+" [ "+e.toString()+" ]\n"); } public void windowDeactivated(WindowEvent e){ append(e.paramString()+" [ "+e.toString()+" ]\n"); } } For further information go to http://www.w3schools.com/js/js_events.asp Use of components A JLabel type of object (label) represents a component which places a text on a display area. A label is made of single line of static text which cannot be modified by the user but can be changed from the program. A JButton type of object (button) is a component which places a labeled button on a display area. A JTextField type of object defines an editing control of the text on a single line. It is useful for the interrogation of the user regarding some values.

98


A JTextArea type of object defines an editing control of the text on multiple lines. It is useful for editing texts, inserting comments, etc. A JCheckbox type of object (commuter) represents a component which can exist in two states: “selected” or “unselected” (on/off). The user’s action on a computer will turn its state into the complementary state of the initial state. It is used to take on an option from the user. A JRadioButton type of object defines a group of commuters and the user can select only one of them. Usually, these components are also called radio buttons. A JComboBox type of object defines a list of options and the user can select only one. At a certain moment, only one option in the list is visible, the selected one. A JComboBox component is accompanied by a button labeled with a vertical arrow which displays the entire list if pressed, so that the user may select a certain option. A JList type of object defines an option list which can be set so that the user may select one option or several. All the options in the list are visible according to the size limitation of the graphical component. A JScrollbar type of object defines a horizontal or vertical scrollbar. It is useful as it provides the user with a suggestive way of selecting a certain value from a set.

99


REFERENCES: 1. Andy Budd, Cameron Moll & Simon Collison: CSS Mastery (APress, 2006, ISBN 1590596145). 2. Cascading Style Sheets, level 1, W3C Recommendation 17 Dec 1996, revised 11 Jan 1999, http://www.w3.org/TR/CSS1. 3. Cascading Style Sheets (CSS) by Example, Steve Callihan. 4. Head First HTML with CSS & XHTML http://books.google.ro/books?id=589iSbn9WYkC 5. Joe Barta`s Tutorials (info.cs.pub.ro) 6. VA, Do you need to learn HTML? http://www.craftedweb.com/website-development/doyou-need-to-learn-html/ 7. http://www.ecursuri.ro/cursuri-online/html-pe-intelesul-tuturor 8. http://www.marplo.net/html/ 9. http://www.w3schools.com/css/css_syntax.asp 10. http://www.w3.org/MarkUp/Guide/Style 11. http://andrei.clubcisco.ro/cursuri/4pw/curs02.pdf 12. http://plomar.uv.ro/html/ 13. http://www.marplo.net/curs_css/ 14. http://www.w3schools.com 15. https://en.wikipedia.org/wiki/Best_coding_practices 16. http://dsq-sds.org/article/viewFile/4632/3946/12630

100


USE OF W3SCHOOLS IMPLIES AN AGREEMENT TO THE FOLLOWING: Copyright Information All pages and graphics on this web site are the property of the company Refsnes Data. Pages, code or other content from W3Schools may not be redistributed or reproduced in any way, shape, or form without the written permission of Refsnes Data. Failure to do so is a violation of copyright laws. Fair Use Fair use defines W3Schools' exceptions to the rights protected by copyright laws. Fair use of W3Schools includes using copyrighted material:  In research  In news reporting  In citations  In commentary Fair use of W3Schools also includes:  Linking to W3Schools  Adding W3Schools to search engines  Library archiving W3Schools Using W3Schools in Teaching Fair use includes using copyrighted material in teaching under this balancing: Favorable Use:  Copying examples and code snippets for non-profit teaching and research.  Copying small quantities, appropriate for classroom teaching. Not Favorable Use:  Copying for profitable or commercial use.  Massive or verbatim copying.  Copying large quantities. Linking to W3Schools: Any web site may link to any of the pages on W3Schools. However, pages from W3Schools may not be embedded in a frame from the referring site, without the written permission of Refsnes Data. 101


Warranties: W3Schools is provided without warranty of any kind. There are no guarantees that use of the site will not be subject to interruptions. All direct or indirect risk related to use of the site is borne entirely by the user. All code provided by W3Schools is provided as examples without warranties to performance, fitness, merchantability, and/or any other warranty (whether expressed or implied). W3Schools may contain inaccuracies or errors. Refsnes Data makes no guarantees regarding the accuracy of the site or its contents. If you discover that the site or its contents contains errors, please contact us so these can be corrected. Contact address: support@w3schools.com

102


Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.