1 / 54

1. Program Structure in Java

1. Program Structure in Java. 1.1 Java Program Basic Elements 1.2 Example of a Java Program 1.3 Java P rogram Structure. Program Structure in Java. Java Program Basic Elements. 1.1.1 Identif iers. Used for representation of different program structures

rene
Download Presentation

1. Program Structure in Java

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 1. Program Structure in Java • 1.1 Java Program Basic Elements • 1.2 Example of a Java Program • 1.3 Java Program Structure

  2. Program Structure in Java Java Program Basic Elements 1.1.1 Identifiers • Used for representation of different program structures • Java-letteris characterfor which method Character.isJavaLetterreturnstrue • Java-digitis characterfor which method Character.isJavaLetterreturnst false, but method Character.isJavaLetterOrDigitreturnstrue • Java is case-sensitive language, there is no length-limit for identifiers

  3. Program Structure in Java Java Program Basic Elements Correct Wrong java_language element 1 (whitespace) numberSum p*218 (*) SUM class (reserved word) element2 2elem (begins with digit) p218 1.1.1 Identifiers - examples

  4. Program Structure in Java 1.2 Example of a Java Program(1/3) Steps for solving a problem using a computer : • Complete understanding of the problem • Distinguishing objects andtheir 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

  5. Program Structure in Java 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. Results: Program Structure in Java 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; Year: 7% 8% 1 1.07 1.08 2 1.144 1.166 3 1.225 1.259 ... 10 1.967 2.158 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); } }

  7. 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. Correct integer expressionsWrong integer expressions 19>>3 (int)true 0x33 + 033 + 33 099 + 1//bad octal num 12L + 45 / 2 % 3 (char) ('a' + 1) ClassesByte,Integer and Math System.out.println(Byte.MAX_VALUE); int i = Integer("123").intValue(); System.out.println(Math.sin( Math.PI / 2 )); Primitive Data Types 2.3 Integer Data Types- examples

  9. Primitive Data Types 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. Primitive Data Types Operators on Primitive Data Types Examples x == 4 letter != 'd' 45 < length x >= y 2.5.2 Operators (1/7) • Relational operators == equal != unequal <less <= less or equal >greater >= greater or equal

  11. Primitive Data Types Operators on Primitive Data Types 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 ); 2.5.2 Operators (2/7) • Arithmetical operators + unary plus - unary minus * multiplication / division % modulo + addition • subtraction ++ prefix or postfixaddition operator -- prefix or postfixsubtractionoperator

  12. Primitive Data Types Operators on Primitive Data Types Examples byte b1 = 9; // eight binary digits: 00001001 System.out.println(1 << 3); // Prints 8 System.out.println(-1 << 3); // Prints -8 System.out.println(17 >> 3); // Prints 2 System.out.println(-17 >> 3); // Prints -3 System.out.println(17 >>> 3); // Prints 2 System.out.println(-17 >>> 3); // Prints 536870909 System.out.println(1 << 35); // Prints 8 2.5.2 Operators (3/7) • Bitwise operators << shift left >> shift right with sign bit >>>shift right with zero fill

  13. Primitive Data Types Operators on Primitive Data Types Examples (bitwise operations) System.out.println(~7); // prints -8 System.out.println(7 & 9); // prints 1 System.out.println(7 | 9); // prints 15 System.out.println(7 ^ 9); // prints 14 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 XORor bitwise XOR && conditional AND i || conditional OR

  14. Primitive Data Types Operators on Primitive Data Types Examples System.out.println( (2 < 3) ? 5 : 6 ); // prints 5 System.out.println( false ? 'a' : 'b' ); // 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 2.5.2 Operators (5/7) • Special operators ? : conditional operator (typeName) explicit type conversion – unary cast operator + string concatenation

  15. Primitive Data Types Operators on Primitive Data Types 2.5.2 Operators (6/7) • Assignment operators • simple assignment = • arithmetic compound assignment operators: *=, /=, %=, +=, ‑= • shift compound assignment operators: <<=, >>=, >>>= • boolean logical compound assignment operators: &=, ^=, |=

  16. Primitive Data Types Operators on Primitive Data Types 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()

  17. Primitive Data Types Operators on Primitive Data Types 2.5.2 Operators - priority

  18. 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.7breakStatement • 3.8continue Statement • 3.9return Statement

  19. Statements Block VariableDeclaration VariableDeclarationId VariableInitializer 3.1.1 Local Variable Declaration • In Java, all variables must be declared before usage • Local variable is declared inside a block

  20. Statements Block 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); } } 3.1.1 Declarations- examples

  21. Statements Conditional Statements SwitchBlock SwitchBlockStatsGroup SwitchLabel 3.4.3switch Statement (1/2) • Multiple alternatives • It is commonly used with breakstatement

  22. Statements Conditional Statements 3.4.3 switch Statement(2/2) • Value of switch statement condition must be one of the basic types char, byte, shortor int • Allowed operators for creating constant expressions: • explicit conversions in type String or in other basic type • unary operators +, -, ~ , ! • binary operators *, /, %, +, -, <<, >>, >>>, <, <=, > , >=, ==, !=, &, ^, |, && , || • ternary operator ? : • breakstatementimmediately terminatesswitchstatement – it is used to prevent executing of all alternatives (from exact switch label to the end of the switchblock • switch statement is much more efficient than nested sequence of if statements

  23. Statements Conditional Statements Example:switchandif 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: else System.out.println(“Failed"); System.out.println("Failed"); } 3.4.3switch Statement- example

  24. Statements Iteration Statements ForStep ForBegin ExprStatementList 3.5.3 forStatement (1/2) • for statement has four important parts: • initialisation part (ForBegin) • condition (Expr) • iteration ending part (ForStep) • body – repeating statement(s) (Stat)

  25. Statements Iteration Statements Ekvivalent forstatements 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++;}; 3.5.3 forStatement (2/2) • Initialisation part– declared local variable is visible only inside for statement block • Condition – logical expression – exits the loop forfalsevalue • 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

  26. Statements Iteration Statements 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++ )); } } 3.5.3 forStatement - examples

  27. Statements 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, door switchstatement where it is located • break statement with label doesn’t have to be located in for, while, doorswitchstatement block – flow control is switched behind specified labelled statement

  28. breakstatement with label System.out.println(“begining"); calculation : { if ( userAbort() ){ break calculation; } dataInput(); if ( userAbort() ){ break calculation; } calculate(); printResult(); } System.out.println(“end"); Statements 3.7break Statement– examples (1/2)

  29. breakstatement 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."); } Statements 3.7break Statement– examples (2/2)

  30. 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

  31. Primer – kreiranje apleta import javax.swing.*; import java.awt.*; public class MyApplet extends JApplet { public void init() { getContentPane().add(new JLabel("Aplet!")); } } Prozori i apleti 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

  32. 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> Prozori i apleti 9.3 Pokretanje apleta • Na taj način se može pozvati appletviewer MyApplet.java, a da se izbegne kreiranje HTML fajla • Pokretanje apleta se može ostvariti i korišćenjem Java alata appletviewer • Pošto appletviewertraž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>

  33. Prozori i apleti 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

  34. 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"); Prozori i apleti 9.5 Uvod u interaktivne interfejse – primer (1/2)

  35. Prozori i apleti 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. Prozori i apleti Raspoređivanje komponenti 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)

  37. Prozori i apleti Raspoređivanje komponenti 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. Prozori i apleti Raspoređivanje komponenti 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)

  39. Prozori i apleti Pregled Swing komponenti 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

  40. Prozori i apleti Pregled Swing komponenti 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); 9.8.1 JLabel i ImageIcon - primer

  41. Prozori i apleti Pregled Swing komponenti Primer label1.setToolTipText("Samo tekst!"); label2.setToolTipText("Samo slika!"); label3.setToolTipText("I tekst i slika!"); 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

  42. Prozori i apleti Pregled Swing komponenti 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 pozvatisetEditable(true) • Nove stavke se dodaju pozivom metoda addItem kojem se kao parametar prosleđuje string koji će biti dodat na kraj liste

  43. Prozori i apleti Pregled Swing komponenti 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. Prozori i apleti Pregled Swing komponenti 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); } }

  45. Prozori i apleti Pregled Swing komponenti 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 (iliItemListenerza 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. Prozori i apleti Pregled Swing komponenti 9.8.8 Meniji – primer (1/5)

  47. Prozori i apleti Pregled Swing komponenti 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);

  48. Prozori i apleti Pregled Swing komponenti 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);

  49. Prozori i apleti Pregled Swing komponenti 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);

  50. Prozori i apleti Pregled Swing komponenti 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); } }

More Related