1. program structure in java · 1 1 / 54 1. program structure in java 1.1 java program basic...

27
1 1 / 54 1. Program Structure in Java 1.1 Java Program Basic Elements 1.2 Example of a Java Program 1.3 Java Program Structure 2 / 54 1.1.1 Identifiers Used for representation of different program structures Java-letter is character for which method Character.isJavaLetter returns true Java-digit is character for which method Character.isJavaLetter returnst false, but method Character.isJavaLetterOrDigit returns true Java is case-sensitive language, there is no length-limit for identifiers Java-letter Java-letter Java-digit

Upload: others

Post on 18-Mar-2020

18 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 1. Program Structure in Java · 1 1 / 54 1. Program Structure in Java 1.1 Java Program Basic Elements 1.2 Example of a Java Program 1.3 Java Program Structure 2 / 54 1.1.1 Identifiers

1

1 / 54

1. Program Structure in Java

1.1 Java Program Basic Elements

1.2 Example of a Java Program

1.3 Java Program Structure

2 / 54

1.1.1 Identifiers

Used for representation of different program structuresJava-letter is character for which method Character.isJavaLetterreturns true Java-digit is character for which method Character.isJavaLetterreturnst false, but method Character.isJavaLetterOrDigitreturns trueJava is case-sensitive language, there is no length-limit for identifiers

Java-letter Java-letter

Java-digit

Page 2: 1. Program Structure in Java · 1 1 / 54 1. Program Structure in Java 1.1 Java Program Basic Elements 1.2 Example of a Java Program 1.3 Java Program Structure 2 / 54 1.1.1 Identifiers

2

3 / 54

1.1.1 Identifiers - examples

Correct Wrong

java_language element 1 (whitespace)

numberSum p*218 (*)

SUM class (reserved word)

element2 2elem (begins with digit)

p218

4 / 54

1.2 Example of a Java Program (1/3)

Steps for solving a problem using a computer :

– Complete understanding of the problem

– Distinguishing objects and their characteristics, and construction of the abstract model for the given problem

– Forming of the abstract model

– Realization of the abstract model, using some programming language

– Input the program code in one or more files using some editor

– Compilation

– Executing and testing

Page 3: 1. Program Structure in Java · 1 1 / 54 1. Program Structure in Java 1.1 Java Program Basic Elements 1.2 Example of a Java Program 1.3 Java Program Structure 2 / 54 1.1.1 Identifiers

3

5 / 54

1.2 Example of a Java Program (2/3)

Problem: Computing year inflation factor during the 10 year period for year inflation rates of 7% i 8%.

Global algorithm :– values initialisation;

header creation,– repeating (until max year is reached):

take next year;compute the factors;print computed values;

6 / 54

1.2 Example of a Java Program (3/3)class Inflation{

public static void main(String[] args) {

int year = 0;

float factor7 = 1.0f;

float factor8 = 1.0f;

System.out.println(“Year:\t7%\t8%");do {

year++; // year = year+1;

factor7 = factor7 * 1.07f;

factor8 = factor8 * 1.08f;

System.out.print(year);

System.out.print("\t");

System.out.print( (float)((int)(factor7 * 1000.0f)) / 1000.0f );

System.out.print("\t");

System.out.println((float)((int)(factor8 * 1000.0f)) / 1000.0f );

} while (year < 10);

}

}

Results:Year: 7% 8%

1 1.07 1.08 2 1.144 1.1663 1.225 1.259...10 1.967 2.158

Page 4: 1. Program Structure in Java · 1 1 / 54 1. Program Structure in Java 1.1 Java Program Basic Elements 1.2 Example of a Java Program 1.3 Java Program Structure 2 / 54 1.1.1 Identifiers

4

7 / 54

2. Primitive Data Types

2.1 Importance of Data Types

2.2 Boolean Data Type

2.3 Integer Data Types

2.4 Real Data Types

2.5 Operators on Primitive Data Types

8 / 54

2.3 Integer Data Types - examples

Correct integer expressions Wrong integer expressions19>>3 (int)true

0x33 + 033 + 33 099 + 1 //bad octal num

12L + 45 / 2 % 3

(char) ('a' + 1)

Classes Byte,Integer and Math

System.out.println(Byte.MAX_VALUE);

int i = Integer("123").intValue();

System.out.println(Math.sin( Math.PI / 2 ));

Page 5: 1. Program Structure in Java · 1 1 / 54 1. Program Structure in Java 1.1 Java Program Basic Elements 1.2 Example of a Java Program 1.3 Java Program Structure 2 / 54 1.1.1 Identifiers

5

9 / 54

2.4 Real Data Types (1/2)Values from set of rational numbers– Float – single precision (4 bytes)– Double – double precision (8 bytes)

real constant structure: mantissa, exponent and type mark

10 / 54

2.5.2 Operators (1/7)Relational operators== equal != unequal< less<= less or equal> greater>= greater or equal

Examples

x == 4letter != 'd'45 < lengthx >= y

Page 6: 1. Program Structure in Java · 1 1 / 54 1. Program Structure in Java 1.1 Java Program Basic Elements 1.2 Example of a Java Program 1.3 Java Program Structure 2 / 54 1.1.1 Identifiers

6

11 / 54

2.5.2 Operators (2/7)Arithmetical operators+ unary plus- unary minus* multiplication/ division% modulo+ addition- subtraction

++ prefix or postfix addition operator-- prefix or postfix subtraction operator

Examples- a + 2 * ( b % 3)5 / b / 3 - 1.0

int a = 10; System.out.println( ++a ); System.out.println( a ); int b = 10;System.out.println( b++ ); System.out.println( b );

12 / 54

2.5.2 Operators (3/7)Bitwise operators<< shift left>> shift right with sign bit>>> shift right with zero fill

Examplesbyte b1 = 9; // eight binary digits: 00001001System.out.println(1 << 3); // Prints 8System.out.println(-1 << 3); // Prints -8System.out.println(17 >> 3); // Prints 2System.out.println(-17 >> 3); // Prints -3System.out.println(17 >>> 3); // Prints 2System.out.println(-17 >>> 3); // Prints 536870909System.out.println(1 << 35); // Prints 8

Page 7: 1. Program Structure in Java · 1 1 / 54 1. Program Structure in Java 1.1 Java Program Basic Elements 1.2 Example of a Java Program 1.3 Java Program Structure 2 / 54 1.1.1 Identifiers

7

13 / 54

2.5.2 Operators (4/7)Logical (boolean and bitwise) operators~ bitwise complement! logical complement& logical AND or bitwise AND| logical OR or bitwise OR^ logical XOR or bitwise XOR

&& conditional AND i || conditional OR

Examples (bitwise operations)System.out.println(~7); // prints -8System.out.println(7 & 9); // prints 1System.out.println(7 | 9); // prints 15System.out.println(7 ^ 9); // prints 14

14 / 54

2.5.2 Operators (5/7)Special operators? : conditional operator(typeName) explicit type conversion – unary cast operator + string concatenation

ExamplesSystem.out.println( (2 < 3) ? 5 : 6 ); // prints 5System.out.println( false ? 'a' : 'b' ); // prints b

int i;i = (int)3.14; // conversion from double to intSystem.out.println(i); // prints 3

System.out.println("Novi " + "Sad"); // prints: Novi Sad

Page 8: 1. Program Structure in Java · 1 1 / 54 1. Program Structure in Java 1.1 Java Program Basic Elements 1.2 Example of a Java Program 1.3 Java Program Structure 2 / 54 1.1.1 Identifiers

8

15 / 54

2.5.2 Operators (6/7)

Assignment operatorssimple assignment=

arithmetic compound assignment operators:*=, /=, %=, +=, -=

shift compound assignment operators: <<=, >>=, >>>=

boolean logical compound assignment operators:&=, ^=, |=

16 / 54

2.5.2 Operators (7/7)

Other operatorsInstanceof. (period)[] (brackets) – array element accessnew (class instance creation)

Operators priority is changed by using parenthesis ( )

Page 9: 1. Program Structure in Java · 1 1 / 54 1. Program Structure in Java 1.1 Java Program Basic Elements 1.2 Example of a Java Program 1.3 Java Program Structure 2 / 54 1.1.1 Identifiers

9

17 / 54

2.5.2 Operators - priority

Multiplication, division, modulo* / %

Assignment operators – lowest priority= *= /= %= += -= <<= >>= >>>= &= ^= |=

Conditional operator? :

Conditional OR||

Conditional AND&&

OR|

XOR^

AND&

Equality checking== !=

Relational operators< > <= >= instanceof

Shifting (bitwise)<< >> >>>

Addition, concatenation subtraction+ -

Unary operators. Prefix operators(typeName) ~ ! -- ++ + -

Postfix operators-- ++

The highest priority operators. [] new

CommentOperator

18 / 54

3. Statements3.1 Block

3.2 Empty Statement

3.3 Expression Statement

3.4 Conditional Statements

3.5 Iteration Statements

3.6 Labelled Statement

3.7 break Statement

3.8 continue Statement

3.9 return Statement

Page 10: 1. Program Structure in Java · 1 1 / 54 1. Program Structure in Java 1.1 Java Program Basic Elements 1.2 Example of a Java Program 1.3 Java Program Structure 2 / 54 1.1.1 Identifiers

10

19 / 54

3.1.1 Local Variable DeclarationIn Java, all variables must be declared before usageLocal variable is declared inside a block

Type VariableDeclaration

,final

VariableDeclarationId

= VariableInitializer

VariableDeclaration

Identificator

[ ]

VariableDeclarationId

Expression

ArrayInitializer

VariableInitializer

20 / 54

3.1.1 Declarations - examples

Basic Type Local Variable Declarationint i = 29;

int j, k;

double d2 = i * 2.2;

final char c1, c2 = 'a' ;

boolean logic = false;

Dynamic initialisationclass TriangleHypotenusis {

public static void main (String args []){

double a=3.0, b=4.0; // const init

double c = Math.sqrt(a*a+b*b); // dynamic init

System.out.println("Hypotenusis: " + c);

}

}

Page 11: 1. Program Structure in Java · 1 1 / 54 1. Program Structure in Java 1.1 Java Program Basic Elements 1.2 Example of a Java Program 1.3 Java Program Structure 2 / 54 1.1.1 Identifiers

11

21 / 54

3.4.3 switch Statement (1/2)

Multiple alternativesIt is commonly used with break statement

switchBlockswitch ( )Expr

SwitchBlockStatsGroup

{

switchLabel

}SwitchBlock

ConstExpr

default

case :

:

SwitchLabel

switchLabel BlockStats

SwitchBlockStatsGroup

22 / 54

3.4.3 switch Statement (2/2)

Value of switch statement condition must be one of the basic types char, byte, short or int

Allowed operators for creating constant expressions:– explicit conversions in type String or in other basic type– unary operators +, -, ~ , !– binary operators *, /, %, +, -, <<, >>, >>>, <, <=, >

, >=, ==, !=, &, ^, |, && , ||– ternary operator ? :

break statement immediately terminates switch statement – it is used to prevent executing of all alternatives (from exact switch label to the end of the switch block

switch statement is much more efficient than nested sequence of ifstatements

Page 12: 1. Program Structure in Java · 1 1 / 54 1. Program Structure in Java 1.1 Java Program Basic Elements 1.2 Example of a Java Program 1.3 Java Program Structure 2 / 54 1.1.1 Identifiers

12

23 / 54

3.4.3 switch Statement - example

Example: switch and if statement comparationswitch ( mark ) {

case 5 : if (ocena == 5)

System.out.println(“Excellent"); System.out.println("Excellent");

break;

case 4 : else if (ocena == 4)

System.out.println(“Very good"); System.out.println("Very good");

break;

case 3 : else if (ocena == 3)

System.out.println(“Good"); System.out.println("Good");

break;

case 2 : else if (ocena == 2)

System.out.println(“Satisfact."); System.out.println("Satisfact.");

break;

default: else

System.out.println(“Failed"); System.out.println("Failed");

}

24 / 54

3.5.3 for Statement (1/2)for statement has four important parts:– initialisation part (ForBegin)– condition (Expr)– iteration ending part (ForStep)– body – repeating statement(s) (Stat)

forBegin

for

Expr

Stat(

ForStep

; ; )

ExprStatementList

ForStep

,

StatExpression

ExprStatementList

ExprStatementList

LocalVariableDeclaration

ForBegin

Page 13: 1. Program Structure in Java · 1 1 / 54 1. Program Structure in Java 1.1 Java Program Basic Elements 1.2 Example of a Java Program 1.3 Java Program Structure 2 / 54 1.1.1 Identifiers

13

25 / 54

3.5.3 for Statement (2/2)Initialisation part – declared local variable is visible only inside for statement blockCondition – logical expression – exits the loop for false valueIteration ending part – statement-expression list, executed sequentlyAll three parts are optional, any of them can be missedImmediately loop termination – break, continue, return

Ekvivalent for statements

for( int i = 0; i < 10; i++ ) a[i]=0;

--------------

int i =0;

...

for( ; i < 10; i++ ) a[i]=0;

--------------

for( int i = 0; i < 10; ) {a[i]=0; i++;};

26 / 54

3.5.3 for Statement - examplesExample : printing numbers from 1 to 100 – three versionsclass program {

public static void main(String[] args) {

for( int number = 1; number <= 100; System.out.println( broj++ ));

}

}

------------------------------------------------------------------------------

class program {

public static void main(String[] args) {

for( int number = 1; number <= 100; System.out.println( number ), number ++);

}

}

------------------------------------------------------------------------------

class program {

public static void main(String[] args) {

for( int number = 1; number <= 100; System.out.println( number++ ));

}

}

Page 14: 1. Program Structure in Java · 1 1 / 54 1. Program Structure in Java 1.1 Java Program Basic Elements 1.2 Example of a Java Program 1.3 Java Program Structure 2 / 54 1.1.1 Identifiers

14

27 / 54

3.7 break Statement

Jump statement with triple functionality:– terminating switch statement– terminating iteration statements– “cosmetic” version of goto statementbreak statement without label switches control behind first (innermost) for, while, do or switch statement where it is locatedbreak statement with label doesn’t have to be located in for, while, do or switch statement block – flow control is switched behind specified labelled statement

identificator

break ;

28 / 54

3.7 break Statement – examples (1/2)

break statement with labelSystem.out.println(“begining");

calculation : {

if ( userAbort() ){

break calculation;

}

dataInput();

if ( userAbort() ){

break calculation;

}

calculate();

printResult();

}

System.out.println(“end");

Page 15: 1. Program Structure in Java · 1 1 / 54 1. Program Structure in Java 1.1 Java Program Basic Elements 1.2 Example of a Java Program 1.3 Java Program Structure 2 / 54 1.1.1 Identifiers

15

29 / 54

3.7 break Statement – examples (2/2)

break statement without labelpublic static void main( String [] args){

if ( args.length != 2 ){

System.out.println(“TWO argumets, please!!!");

System.exit(1);

}

char wantedLetter = args[1].charAt(0);

boolean found = false;

for (int i = 0; i < args[0].length(); i++){

if (wantedLetter == args[0].charAt(i) ){

found = true;

break;

}

}

System.out.println(" Wanted letter " + ( found ? “is" : “is not" ) +

" found.");

}

30 / 54

9. Prozori i apleti9.1 Klasa JFrame

9.2 Klasa JApplet

9.3 Pokretanje apleta

9.4 Crtanje

9.5 Uvod u interaktivne interfejse

9.6 Raspoređivanje komponenti

9.7 Model događaja

9.8 Pregled Swing komponenti

9.9 Animacije

Page 16: 1. Program Structure in Java · 1 1 / 54 1. Program Structure in Java 1.1 Java Program Basic Elements 1.2 Example of a Java Program 1.3 Java Program Structure 2 / 54 1.1.1 Identifiers

16

31 / 54

9.2 Klasa JApplet - primer

Dodavanje komponenti se obavlja u redefinisanom metodu init, pozivanjem metoda add, ali je prethodno potrebno dobiti referencu na objekat sadržajnog okna

Apleti ne moraju da imaju implementiran metod main, većse kreiranje odgovarajuće intance apleta i njegovo prikazivanje na ekranu obično vrši od strane sistema

Primer – kreiranje apleta

import javax.swing.*;import java.awt.*;

public class MyApplet extends JApplet {public void init() {getContentPane().add(new JLabel("Aplet!"));

}}

32 / 54

9.3 Pokretanje apleta

Na taj način se može pozvati appletviewer MyApplet.java, a da se izbegne kreiranje HTML fajla

Primer - HTML stranica sa ugrađenim apletom MyApplet<HTML><HEAD>

<TITLE> Nasa web stranica </TITLE></HEAD><BODY>

Ovde je rezultat naseg programa:<APPLET CODE="MyApplet.class" WIDTH=150 HEIGHT=25></APPLET>

</BODY></HTML>

\\ <applet code="MyApplet.class" width=200 height=100></applet>

Pokretanje apleta se može ostvariti i korišćenjem Java alataappletviewerPošto appletviewer traži <applet> tagove da bi pokrenuoaplete <applet> tag se vrlo često ubacuje na početak izvornogfajla (na primer MyApplet.java) pod komentarom:

Page 17: 1. Program Structure in Java · 1 1 / 54 1. Program Structure in Java 1.1 Java Program Basic Elements 1.2 Example of a Java Program 1.3 Java Program Structure 2 / 54 1.1.1 Identifiers

17

33 / 54

9.5 Uvod u interaktivne interfejseZa razliku od proceduralnih programa u kojima se naredbe izvršavaju sekvencijalno, programi koji opisuju interakciju sa korisnikom pomoću grafičkih interfejsa su asinhroniProgram mora biti spreman da odgovori na razne vrste događaja koji se mogu desiti u bilo koje vreme i to redosledom koji program ne može da kontroliše. Osnovne tipove događaja čine oni koji su generisani mišem ili tastaturomProgramiranje vođeno događajima (engl. event-driven programming) - sistemski dodeljena nit se izvršava u petlji čekajući na akcije korisnikaProgramiranje interaktivnih prozorskih aplikacija se svodi na raspoređivanje komponenti u okviru prozora, a zatim i na definisanje metoda koji bi služili za obradu događaja koje te komponente mogu da proizvedu

34 / 54

9.5 Uvod u interaktivne interfejse – primer (1/2)

Primer - aplet koji interaktivno menja sadržaj labele

// <applet code="Dugme.class" width=300 height=75></applet>import javax.swing.*;import java.awt.event.*;import java.awt.*;

public class Dugme extends JApplet {private JButton

d1 = new JButton("Dugme 1"),d2 = new JButton("Dugme 2");

private JLabel txt = new JLabel("Pocetak");

Page 18: 1. Program Structure in Java · 1 1 / 54 1. Program Structure in Java 1.1 Java Program Basic Elements 1.2 Example of a Java Program 1.3 Java Program Structure 2 / 54 1.1.1 Identifiers

18

35 / 54

9.5 Uvod u interaktivne interfejse – primer (2/2)

private ActionListener dl = new ActionListener() {public void actionPerformed(ActionEvent e) {

String name = ((JButton)e.getSource()).getText();txt.setText(name);

}};public void init() {

d1.addActionListener(dl);d2.addActionListener(dl);Container cp = getContentPane();cp.setLayout(new FlowLayout());cp.add(d1);cp.add(d2);cp.add(txt);

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

JFrame frame = new JFrame("Dugme");frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);JApplet applet = new Dugme();applet.init();applet.start();frame.getContentPane().add(applet);frame.setSize(300,75);frame.setVisible(true);

}}

36 / 54

9.6.3 GridLayout

Formira tabelu međusobno jednakih komponenti saodgovarajućim brojem vrsta i kolonaKoristi se verzija metoda add sa jednim argumentom

Komponente će u tabeli biti raspoređene redom kojim se postavljaju na površinu kontejnera tako što se tabela popunjavapo vrstama, od gornjih ka donjim, pri čemu se svaka vrstapopunjava sa leva na desnoBroj vrsta i kolona se zadaje konstruktorom GridLayout(introws, int cols)i u tom slučaju komponente se maksimalnozbijaju

Za određivanje horizontalnog i vertikalnog rastojanja između komponenti koristi se konstruktor GridLayout(int rows, int cols, int hgap, int vgap)

Page 19: 1. Program Structure in Java · 1 1 / 54 1. Program Structure in Java 1.1 Java Program Basic Elements 1.2 Example of a Java Program 1.3 Java Program Structure 2 / 54 1.1.1 Identifiers

19

37 / 54

9.6.3 GridLayout - primer

// <applet code="GridLayout1.class" width=300 height=250></applet>import javax.swing.*;import java.awt.*;

public class GridLayout1 extends JApplet {public void init() {

Container cp = getContentPane();cp.setLayout(new GridLayout(5,3));for(int i = 1; i < 15; i++)

cp.add(new JButton("Button " + i));}public static void main(String[] args) {

JFrame frame = new JFrame("GridLayout1");frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);JApplet applet = new GridLayout1();applet.init();applet.start();frame.getContentPane().add(applet);frame.setSize(300,250);frame.setVisible(true);

}}

38 / 54

9.6.7 Kombinovanje raspoređivača grupisanjem elemenata

Standardna klasa JPanel – kontejner (može da sadržava drugekomponente) i komponenta (može se postaviti na površinuapleta ili drugog panela)

Time je omogućeno proizvoljno složeno ugneždavanjekomponenti, pri čemu svaki panel može posedovati proizvoljnograspoređivača svojih komponenti (na slici – tri panela sa šest komponenti)

Page 20: 1. Program Structure in Java · 1 1 / 54 1. Program Structure in Java 1.1 Java Program Basic Elements 1.2 Example of a Java Program 1.3 Java Program Structure 2 / 54 1.1.1 Identifiers

20

39 / 54

9.8. Pregled Swing komponentiNajčešće korišćene specijalizovane komponente korisničkih interfejsa

Mahom nasleđuju zajedničku osnovnu klasu JComponent

Upotreba svake komponente obuhvata:– Kreiranje objekta komponente

– Uključivanje objekta u neki kontejner

– Komponenti se prijavljuje osluškivač koji će reagovati na odgovarajuće događaje

40 / 54

9.8.1 JLabel i ImageIcon - primer

Primer – tri labele

Icon icon = new ImageIcon("slika.gif");JLabel label1 = new JLabel("Samo tekst", JLabel.CENTER);JLabel label2 = new JLabel(icon, Jlabel.CENTER); // Samo slikaJLabel label3 = new JLabel("Slika i tekst", icon, JLabel.CENTER);label3.setVerticalTextPosition(JLabel.BOTTOM);label3.setHorizontalTextPosition(JLabel.CENTER);

Page 21: 1. Program Structure in Java · 1 1 / 54 1. Program Structure in Java 1.1 Java Program Basic Elements 1.2 Example of a Java Program 1.3 Java Program Structure 2 / 54 1.1.1 Identifiers

21

41 / 54

9.8.2 JToolTip

JToolTip je string koji služi kao uputstvo ili dodatnoobjašnjenje neke komponentePojavljuje se automatski kada pokazivač miša mirujenekoliko sekundi iznad komponente, a nestaje čim se pokazivač miša pomeriDa bismo JToolTip dodelili nekoj komponenti, potrebno jesamo pozvati metod komponente setToolTipText

Primer

label1.setToolTipText("Samo tekst!");label2.setToolTipText("Samo slika!");label3.setToolTipText("I tekst i slika!");

42 / 54

9.8.6 Padajuće liste (JComboBox)

Poput grupe dugmadi tipa JRadioButton, padajuća listaomogućava korisniku da odabere jednu od više ponuđenihmogućnosti, ali je izgled komponente puno kompaktniji

Kada god korisnik odabere neku stavku iz menija, padajuća lista generiše događaj tipa ActionEvent

Padajuća lista inicijalno ne dozvoljava unos teksta sa tastature– da bi se to postiglo potrebno je pozvatisetEditable(true)

Nove stavke se dodaju pozivom metoda addItem kojem se kao parametar prosleđuje string koji će biti dodat na kraj liste

Page 22: 1. Program Structure in Java · 1 1 / 54 1. Program Structure in Java 1.1 Java Program Basic Elements 1.2 Example of a Java Program 1.3 Java Program Structure 2 / 54 1.1.1 Identifiers

22

43 / 54

9.8.6 Padajuće liste – primer (1/2)

//<applet code="ComboBoxDemo.class" width=200 height=125></applet>import javax.swing.*;import java.awt.event.*;import java.awt.*;public class ComboBoxDemo extends JApplet {private String[] description = {

"Prva stavka", "Druga stavka", "Treca stavka", "Cetvrta stavka","Peta stavka", "Sesta stavka", "Sedma stavka", "Osma stavka"

};private JTextField jtf = new JTextField(15);private JComboBox jcb = new JComboBox();private JButton jb = new JButton("Add items");private int count = 0;public void init() {

for(int i = 0; i < 4; i++)jcb.addItem(description[count++]);

jtf.setEditable(false);

44 / 54

9.8.6 Padajuće liste - primer (2/2)jb.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {if(count < description.length)

jcb.addItem(description[count++]);}

});jcb.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {jtf.setText("Index: "+ jcb.getSelectedIndex() + " " +

((JComboBox)e.getSource()).getSelectedItem());}

});jcb.setEditable(true);Container cp = getContentPane();cp.setLayout(new FlowLayout());cp.add(jtf);cp.add(jcb);cp.add(jb);

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

JFrame frame = new JFrame("JComboBox");frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);JApplet applet = new ComboBoxDemo();applet.init();applet.start();frame.getContentPane().add(applet);frame.setSize(200,125);frame.setVisible(true);

}}

Page 23: 1. Program Structure in Java · 1 1 / 54 1. Program Structure in Java 1.1 Java Program Basic Elements 1.2 Example of a Java Program 1.3 Java Program Structure 2 / 54 1.1.1 Identifiers

23

45 / 54

9.8.8 Meniji

Svaki kontejner na njavišem nivou hijerarhije, kao što su JAplet, JFrame, JDialog i njihovi naslednici, može da sadrži najviše jednu traku sa menijima - metod setJMenuBar koji kao parametar prihvata objekat klase JMenuBarSvaki JMenuBar može da poseduje više menija predstavljenih klasom JMenu, a svaki meni može da sadrži više stavki koje su predstavljene klasama JMenuItem, JCheckBoxMenuItem i JRadioButtonMenuItem. Stavka u meniju može biti i drugi meni Sve klase kojima su predstavljene stavke u meniju nasleđuju klasu AbstractButtonBilo kojoj stavki može biti pridružen osluškivač tipa ActionListener(iliItemListener za JCheckBoxMenuItem)Meniji podržavaju dva načina skraćenog aktiviranja stavki sa tastature: mnemonike i akceleratore – metodi setMnemonic + konstanta klase KeyEvent, odnosno setAccelerator + objekat klase KeyStroke (kombinacija 'Ctrl', 'Alt' ili 'Shift‘ sa odgovarajućom tipkom)

46 / 54

9.8.8 Meniji – primer (1/5)

Page 24: 1. Program Structure in Java · 1 1 / 54 1. Program Structure in Java 1.1 Java Program Basic Elements 1.2 Example of a Java Program 1.3 Java Program Structure 2 / 54 1.1.1 Identifiers

24

47 / 54

9.8.8 Meniji – primer (2/5)

//<applet code="MenuDemo.class" width=410 height=275></applet>import java.awt.*;import java.awt.event.*;import javax.swing.*;public class MenuDemo extends JApplet {JTextArea jta;public void init() {

JMenuBar menuBar;JMenu menu, submenu;JMenuItem menuItem;JCheckBoxMenuItem cbMenuItem;JRadioButtonMenuItem rbMenuItem;ActionListener al = new ActionListener() {

public void actionPerformed(ActionEvent e) {jta.append("Action [" + e.getActionCommand() + "] performed!\n");

}};//kreiranje trake sa menijimamenuBar = new JMenuBar();setJMenuBar(menuBar);

//kreiranje prvog menijamenu = new JMenu("A Menu");menu.setMnemonic(KeyEvent.VK_A);menuBar.add(menu);

48 / 54

9.8.8 Meniji – primer (3/5)

//tri stavke tipa JMenuItemmenuItem = new JMenuItem("A text-only menu item", KeyEvent.VK_T);menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_1,

ActionEvent.CTRL_MASK));menuItem.addActionListener(al);menu.add(menuItem);ImageIcon smiley = new ImageIcon("smiley.gif");menuItem = new JMenuItem("Both text and icon", smiley);menuItem.setMnemonic(KeyEvent.VK_B);menuItem.addActionListener(al);menu.add(menuItem);menuItem = new JMenuItem(smiley);menuItem.setMnemonic(KeyEvent.VK_D);menuItem.addActionListener(al);menuItem.setActionCommand("An image-only menu item");menu.add(menuItem);

//dve stavke tipa JRadioButtonMenuItem

menu.addSeparator();ButtonGroup group = new ButtonGroup();rbMenuItem = new JRadioButtonMenuItem("A radio button menu item");rbMenuItem.setSelected(true);rbMenuItem.setMnemonic(KeyEvent.VK_R);rbMenuItem.addActionListener(al);group.add(rbMenuItem);menu.add(rbMenuItem);

Page 25: 1. Program Structure in Java · 1 1 / 54 1. Program Structure in Java 1.1 Java Program Basic Elements 1.2 Example of a Java Program 1.3 Java Program Structure 2 / 54 1.1.1 Identifiers

25

49 / 54

9.8.8 Meniji – primer (4/5)rbMenuItem = new JRadioButtonMenuItem("Another one");rbMenuItem.setMnemonic(KeyEvent.VK_O);rbMenuItem.addActionListener(al);group.add(rbMenuItem);menu.add(rbMenuItem);

//dve stavke tipa JCheckBoxMenuItemmenu.addSeparator();cbMenuItem = new JCheckBoxMenuItem("A check box menu item");cbMenuItem.setMnemonic(KeyEvent.VK_C);cbMenuItem.addActionListener(al);menu.add(cbMenuItem);cbMenuItem = new JCheckBoxMenuItem("Another one");cbMenuItem.setMnemonic(KeyEvent.VK_H);cbMenuItem.addActionListener(al);menu.add(cbMenuItem);

//podmenimenu.addSeparator();submenu = new JMenu("A submenu");submenu.setMnemonic(KeyEvent.VK_S);menuItem = new JMenuItem("An item in the submenu");menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_2,

ActionEvent.CTRL_MASK));menuItem.addActionListener(al);submenu.add(menuItem);menuItem = new JMenuItem("Another item");menuItem.addActionListener(al);submenu.add(menuItem);menu.add(submenu);

50 / 54

9.8.8 Meniji – primer (5/5)

//drugi menimenu = new JMenu("Another Menu");menu.setMnemonic(KeyEvent.VK_N);menuBar.add(menu);

//tekstualna povrsinajta = new JTextArea();jta.setEditable(false);getContentPane().add(new JScrollPane(jta));

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

JFrame frame = new JFrame("JMenu");frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);JApplet applet = new MenuDemo();applet.init();applet.start();frame.getContentPane().add(applet);frame.setSize(410,275);frame.setVisible(true);

}}

Page 26: 1. Program Structure in Java · 1 1 / 54 1. Program Structure in Java 1.1 Java Program Basic Elements 1.2 Example of a Java Program 1.3 Java Program Structure 2 / 54 1.1.1 Identifiers

26

51 / 54

9.9 AnimacijeAnimacije predstavljaju nizove slika koje se na ekranu prikazuju jednanakon drugeNajprirodniji način za programiranje animacije da se kreira zasebna nit koja će animaciju izvršavati - nit možemo kreirati eksplicitno, nasleđivanjem klase Thread ili implementiranjem interfejsa Runnable i redefinisanjem odgovarajućeg metoda runJednostavan mehanizam programiranja aplikacija – koristeći objekat klase javax.swing.Timer, koji nezavisno, bez uticaja korisnika, generiše dogadjaje u pravilnim vremenskim intervalimaProgramiranje animacije - kreiramo brojač i reagujemo na svaki događaj koji on generiše tako što ćemo prikazati narednu sliku animacijeDogađaji generisani brojačem su tipa ActionEventBrojač startujemo pozivanjem metoda start (po pravilu bi ga trebalo pozvati samo jednom za svo vreme postojanja brojača)Brojač takođe ima metod stop koji se poziva da bi se zaustavilo generisanje događaja. Ako smo zaustavili brojač i želimo ponovo da ga pokrenemo, moramo pozvati njegov metod restart

52 / 54

9.9 Animacije – primer (1/3)

//<applet code="ScrollingText.class" width=400 height=150></applet>import java.awt.*;import java.awt.event.*;import javax.swing.*;

public class ScrollingText extends JApplet {Timer brojac;String poruka = "Poruka koja se skroluje..."; int pozicijaPoruke = -1;int sirinaPoruke, visinaPoruke;int sirinaKaraktera;

Page 27: 1. Program Structure in Java · 1 1 / 54 1. Program Structure in Java 1.1 Java Program Basic Elements 1.2 Example of a Java Program 1.3 Java Program Structure 2 / 54 1.1.1 Identifiers

27

53 / 54

9.9 Animacije – primer (2/3)public void init() {

JPanel display = new JPanel() {public void paintComponent(Graphics g) {

super.paintComponent(g);g.drawString(poruka, getSize().width - pozicijaPoruke,

getSize().height/2 + visinaPoruke/2);}

};getContentPane().add(display);display.setBackground(Color.white);display.setForeground(Color.red);Font fontPoruke = new Font("Monospaced", Font.BOLD, 30);display.setFont(fontPoruke);FontMetrics fm = getFontMetrics(fontPoruke);sirinaPoruke = fm.stringWidth(poruka);visinaPoruke = fm.getAscent();sirinaKaraktera = fm.charWidth('P');

}

public void start() {if (brojac == null) {

ActionListener al = new ActionListener() {public void actionPerformed(ActionEvent evt) {

pozicijaPoruke += sirinaKaraktera/2;if (getSize().width - pozicijaPoruke + sirinaPoruke < 0)

pozicijaPoruke = -1;repaint();

}};

54 / 54

9.9 Animacije – primer (3/3)brojac = new Timer(50, al);brojac.start();

} else {brojac.restart();

}}public void stop() {

brojac.stop();}

private static JApplet applet;public static void main(String[] args) {

JFrame frame = new JFrame("ScrollingText");frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);applet = new ScrollingText();applet.init();applet.start();

frame.addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent e) {

applet.stop();applet.destroy();

}});frame.getContentPane().add(applet);frame.setSize(400,150);frame.setVisible(true);

}}