Struktura programa u Javi

Download Report

Transcript Struktura programa u Javi

1. Program Structure in Java

1.1 Java Program Basic Elements

1.2 Example of a Java Program

1.3 Java Program Structure
1 / 54
1.1.1 Identifiers
Java-letter
Java-letter
Java-digit

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
2 / 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
3 / 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
4 / 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;
5 / 54
1.2 Example of a Java Program (3/3)
class Inflation{
public static void main(String[] args) {
Year:
int year = 0;
float factor7 = 1.0f;
float factor8 = 1.0f;
System.out.println(“Year:\t7%\t8%");
do {
year++;
Results:
// year = year+1;
factor7 = factor7 * 1.07f;
1
2
3
...
10
7%
8%
1.07
1.144
1.225
1.08
1.166
1.259
1.967
2.158
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);
}
}
6 / 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

7 / 54
2.3 Integer Data Types
- examples
Correct integer expressions
Wrong integer expressions
19>>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 ));
8 / 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
9 / 54
2.5.2 Operators (1/7)

Relational operators
== equal
!= unequal
< less
<= less or equal
> greater
>= greater or equal
Examples
x == 4
letter != 'd'
45 < length
x >= y
10 / 54
2.5.2 Operators (2/7)

Arithmetical operators
+
*
/
%
+
unary plus
unary minus
multiplication
division
modulo
addition
- subtraction
Examples
- a + 2 * ( b % 3)
5 / b / 3 - 1.0
int a = 10;
System.out.println(
System.out.println(
int b = 10;
System.out.println(
System.out.println(
++a );
a );
b++ );
b );
++ prefix or postfix addition operator
-- prefix or postfix subtraction operator
11 / 54
2.5.2 Operators (3/7)

Bitwise operators
<< shift left
>> shift right with sign bit
>>> shift right with zero fill
Examples
byte b1 = 9;
// eight binary
System.out.println(1 << 3);
System.out.println(-1 << 3);
System.out.println(17 >> 3);
System.out.println(-17 >> 3);
System.out.println(17 >>> 3);
System.out.println(-17 >>> 3);
System.out.println(1 << 35);
digits: 00001001
// Prints 8
// Prints -8
// Prints 2
// Prints -3
// Prints 2
// Prints 536870909
// Prints 8
12 / 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);
System.out.println(7 & 9);
System.out.println(7 | 9);
System.out.println(7 ^ 9);
//
//
//
//
prints
prints
prints
prints
-8
1
15
14
13 / 54
2.5.2 Operators (5/7)

Special operators
? :
conditional operator
(typeName) explicit type conversion – unary cast operator
+
string concatenation
Examples
System.out.println( (2 < 3) ? 5 : 6 );
System.out.println( false ? 'a' : 'b' );
// prints 5
// prints b
int i;
i = (int)3.14; // conversion from double to int
System.out.println(i); // prints 3
System.out.println("Novi " + "Sad"); // prints: Novi Sad
14 / 54
2.5.2 Operators (6/7)

Assignment operators
 simple assignment
=
 arithmetic compound assignment operators:
*=, /=, %=, +=, -=
 shift compound assignment operators:
<<=, >>=, >>>=
 boolean logical compound assignment operators:
&=, ^=, |=
15 / 54
2.5.2 Operators (7/7)

Other operators
Instanceof
. (period)
[] (brackets) – array element access
new (class instance creation)

Operators priority is changed by using parenthesis ( )
16 / 54
2.5.2 Operators - priority
Operator
Comment
. [] new
The highest priority operators
-- ++
Postfix operators
(typeName) ~ ! -- ++ + -
Unary operators. Prefix operators
* / %
Multiplication, division, modulo
+ -
Addition, concatenation subtraction
<< >> >>>
Shifting (bitwise)
< > <= >= instanceof
Relational operators
== !=
Equality checking
&
AND
^
XOR
|
OR
&&
Conditional AND
||
Conditional OR
? :
Conditional operator
= *= /= %= += -= <<= >>= >>>= &= ^= |=
Assignment operators – lowest priority
17 / 54
3. Statements

3.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
18 / 54
3.1.1 Local Variable Declaration


In Java, all variables must be declared before usage
Local variable is declared inside a block
,
final
Type
VariableDeclaration
=
VariableInitializer
VariableDeclarationId
VariableDeclaration
Expression
[
]
Identificator
VariableDeclarationId
ArrayInitializer
VariableInitializer
19 / 54
3.1.1 Declarations - examples
Basic Type Local Variable Declaration
int i = 29;
int j, k;
double d2 = i * 2.2;
final char c1, c2 = 'a' ;
boolean logic = false;
Dynamic initialisation
class 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);
}
}
20 / 54
3.4.3 switch Statement (1/2)


Multiple alternatives
It is commonly used with break statement
switch
(
Expr
)
SwitchBlockStatsGroup
switchBlock
switchLabel
{
}
SwitchBlock
case
switchLabel
ConstExpr
:
BlockStats
SwitchBlockStatsGroup
default
:
SwitchLabel
21 / 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 if
statements
22 / 54
3.4.3 switch Statement
- example
Example: switch and if statement comparation
switch ( 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:
System.out.println(“Failed");
else
System.out.println("Failed");
}
23 / 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
;
(
ForStep
;
)
Stat
ExprStatementList
ExprStatementList
LocalVariableDeclaration
ForBegin
ForStep
,
StatExpression
ExprStatementList
24 / 54
3.5.3 for Statement (2/2)

Initialisation part – declared local variable is visible only inside
for statement block

Condition – logical expression – exits the loop for false value

Iteration ending part – statement-expression list, executed
sequently

All three parts are optional, any of them can be missed

Immediately 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++;};
25 / 54
3.5.3 for Statement
- examples
Example : printing numbers from 1 to 100 – three versions
class 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++ ));
}
}
26 / 54
3.7 break Statement

Jump statement with triple functionality:
– terminating switch statement
– terminating iteration statements
– “cosmetic” version of goto statement


break statement without label switches control behind first
(innermost) for, while, do or switch statement where it is
located
break 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
;
27 / 54
3.7 break Statement
– examples (1/2)
break statement with label
System.out.println(“begining");
calculation : {
if ( userAbort() ){
break calculation;
}
dataInput();
if ( userAbort() ){
break calculation;
}
calculate();
printResult();
}
System.out.println(“end");
28 / 54
3.7 break Statement
– examples (2/2)
break statement without label
public 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.");
}
29 / 54
9. Prozori i apleti

9.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
30 / 54
9.2 Klasa JApplet - primer
Primer – kreiranje apleta
import javax.swing.*;
import java.awt.*;
public class MyApplet extends JApplet {
public void init() {
getContentPane().add(new JLabel("Aplet!"));
}
}

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
31 / 54
9.3 Pokretanje apleta
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>


Pokretanje apleta se može ostvariti i korišćenjem Java alata
appletviewer
Pošto appletviewer traži <applet> tagove da bi pokrenuo
aplete <applet> tag se vrlo često ubacuje na početak izvornog
fajla (na primer MyApplet.java) pod komentarom:
\\ <applet code="MyApplet.class" width=200 height=100></applet>

Na taj način se može pozvati appletviewer
MyApplet.java, a da se izbegne kreiranje HTML fajla
32 / 54
9.5 Uvod u interaktivne interfejse




Za razliku od proceduralnih programa u kojima se naredbe
izvršavaju sekvencijalno, programi koji opisuju interakciju sa
korisnikom pomoću grafičkih interfejsa su asinhroni
Program 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 tastaturom
Programiranje vođeno događajima (engl. event-driven
programming) - sistemski dodeljena nit se izvršava u petlji
čekajući na akcije korisnika
Programiranje 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
33 / 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");
34 / 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);
}
}
35 / 54
9.6.3 GridLayout

Formira tabelu međusobno jednakih komponenti sa
odgovarajućim brojem vrsta i kolona

Koristi 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 popunjava
po vrstama, od gornjih ka donjim, pri čemu se svaka vrsta
popunjava sa leva na desno

Broj vrsta i kolona se zadaje konstruktorom GridLayout(int
rows, int cols)i u tom slučaju komponente se maksimalno
zbijaju

Za određivanje horizontalnog i vertikalnog rastojanja između
komponenti koristi se konstruktor GridLayout(int rows,
int cols, int hgap, int vgap)
36 / 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);
}
}
37 / 54
9.6.7 Kombinovanje raspoređivača
grupisanjem elemenata

Standardna klasa JPanel – kontejner (može da sadržava
druge komponente) i komponenta (može se postaviti na
površinu apleta ili drugog panela)

Time je omogućeno proizvoljno složeno ugneždavanje
komponenti, pri čemu svaki panel može posedovati proizvoljnog
raspoređivača svojih komponenti (na slici – tri panela sa šest
komponenti)
38 / 54
9.8. Pregled Swing komponenti

Najč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
39 / 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 slika
JLabel label3 = new JLabel("Slika i tekst", icon, JLabel.CENTER);
label3.setVerticalTextPosition(JLabel.BOTTOM);
label3.setHorizontalTextPosition(JLabel.CENTER);
40 / 54
9.8.2 JToolTip



JToolTip je string koji služi kao uputstvo ili dodatno
objašnjenje neke komponente
Pojavljuje se automatski kada pokazivač miša miruje
nekoliko sekundi iznad komponente, a nestaje čim se
pokazivač miša pomeri
Da bismo JToolTip dodelili nekoj komponenti, potrebno je
samo pozvati metod komponente setToolTipText
Primer
label1.setToolTipText("Samo tekst!");
label2.setToolTipText("Samo slika!");
label3.setToolTipText("I tekst i slika!");
41 / 54
9.8.6 Padajuće liste (JComboBox)

Poput grupe dugmadi tipa JRadioButton, padajuća lista
omogućava korisniku da odabere jednu od više ponuđenih
moguć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 pozvati
setEditable(true)

Nove stavke se dodaju pozivom metoda addItem kojem se
kao parametar prosleđuje string koji će biti dodat na kraj liste
42 / 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);
43 / 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);
}
}
" +
44 / 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 JMenuBar
 Svaki 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
AbstractButton

Bilo 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)
45 / 54
9.8.8 Meniji – primer (1/5)
46 / 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 menijima
menuBar = new JMenuBar();
setJMenuBar(menuBar);
//kreiranje prvog menija
menu = new JMenu("A Menu");
menu.setMnemonic(KeyEvent.VK_A);
menuBar.add(menu);
47 / 54
9.8.8 Meniji – primer (3/5)
//tri stavke tipa JMenuItem
menuItem = 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);
48 / 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 JCheckBoxMenuItem
menu.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);
//podmeni
menu.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);
49 / 54
9.8.8 Meniji – primer (5/5)
//drugi meni
menu = new JMenu("Another Menu");
menu.setMnemonic(KeyEvent.VK_N);
menuBar.add(menu);
//tekstualna povrsina
jta = 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);
}
}
50 / 54
9.9 Animacije

Animacije predstavljaju nizove slika koje se na ekranu prikazuju jedna
nakon druge

Najprirodniji 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 run

Jednostavan mehanizam programiranja aplikacija – koristeći objekat
klase javax.swing.Timer, koji nezavisno, bez uticaja korisnika,
generiše dogadjaje u pravilnim vremenskim intervalima
Programiranje animacije - kreiramo brojač i reagujemo na svaki događaj
koji on generiše tako što ćemo prikazati narednu sliku animacije
 Događaji generisani brojačem su tipa ActionEvent



Brojač 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
51 / 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;
52 / 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();
}
};
53 / 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);
}
}
54 / 54