Your SlideShare is downloading. ×
0
Simple Control Structures boolean s, the  if  statement switch-case
What are control structures? <ul><li>You can’t do very much if your program consists of just a list of commands to be done...
boolean <ul><li>boolean  is one of the eight primitive types  </li></ul><ul><ul><li>boolean s are used to make yes/no deci...
Declaring  boolean   variables <ul><li>boolean   variables are declared like any other kind of variable: </li></ul><ul><ul...
Numeric comparisons <ul><li>The following numeric comparisons each give a  boolean  result: </li></ul><ul><ul><li>x < y  /...
The  if  statement <ul><li>The  if  statement has the form: </li></ul><ul><ul><li>if ( boolean-expression )   statement </...
Compound statements <ul><li>We can use braces to group together several statements into one “compound” statement: </li></u...
The  if  statement again <ul><li>The  if   statement controls  one  other statement, but it can be a compound statement </...
Flowchart for the  if   statement condition? statement true false
The  if-else  statement <ul><li>The   if-else   statement chooses which of  two  statements to execute </li></ul><ul><li>T...
Example  if-else  statements <ul><li>if (x >= 0) absX = x; else absX = -x; </li></ul><ul><li>if (itemCost <= bankBalance) ...
Flowchart for the  if-else   statement condition? true statement-1 statement-2 false
Aside: the “mod” operator <ul><li>The modulo, or “mod,” operator returns the remainder of an integer division </li></ul><u...
Nesting  if   (or  if-then ) statements <ul><li>A year is a leap year if it is divisible by 4 but not by 100, unless it is...
Operations on  boolean s <ul><li>Assume   p   and   q   are booleans </li></ul><ul><li>There are four basic operations on ...
Simpler tests <ul><li>A simpler leap-year test: </li></ul><ul><ul><li>if (year % 4 == 0 &&   (year % 100 != 0 || year % 40...
The  if-else  statement <ul><li>The  if-else  statement chooses which of  two  statements to execute </li></ul><ul><li>The...
Dangling Else <ul><li>Compiler cannot determine which “if” an “else” belongs to if there are no braces </li></ul><ul><ul><...
Multiway selection <ul><li>Multiple conditions, each of which causes a different block of statements to execute </li></ul>...
“ if” ladder <ul><li>Just a nicer way to write multiway selection  </li></ul><ul><li>if (operation == ‘a’) </li></ul><ul><...
The “switch” statement <ul><li>Selects among different statements based on a single integer or character expression </li><...
Sample switch statement <ul><li>switch (SouperSandwichOrder) </li></ul><ul><li>{ </li></ul><ul><li>case 1 : cheese = 1; </...
“ break” optimisation <ul><li>If break is omitted, control continues to next statement in the switch </li></ul><ul><li>swi...
Characters in “switch” <ul><li>char Operation = Keyboard.readChar (“What to do?”); </li></ul><ul><li>switch (Operation) </...
Boolean operators ! || && Java true if parameter is false; false if parameter is true; NOT true if at least one parameter ...
Operator precedence <ul><li>Now that we have seen how operators can be mixed, we need precedence rules for all operators <...
Reversing expressions <ul><li>Use ! operator to reverse meaning of boolean expression, e.g., </li></ul><ul><ul><li>if (mar...
Afvinkopdracht 5: Tic-tac-toe
Graphic programming The GUI revisited
<ul><li>Java, unlike C & C++, has standard packages for graphics </li></ul><ul><li>2 related packages and sub-packages sup...
<ul><li>Swing is much more platform independent  </li></ul><ul><ul><li>Graphical components are  pre-built  and are simply...
Frames <ul><li>A  frame  is a top level window which is a  container  for graphical components (canvas, buttons, menus etc...
import  javax.swing.*; class MyFrame extends JFrame { public MyFrame() {   setTitle(&quot;My first graphics program&quot;)...
 
<ul><li>A class  MyFrame  is defined which is a sub-class of  JFrame </li></ul><ul><ul><li>A title is added </li></ul></ul...
Swing inheritance hierarchy <ul><li>The JFrame class inherits attributes from higher level container classes </li></ul><ul...
JFrame JComponent JPanel … .. Component Frame Window Container
<ul><li>Most swing components (for example  JPanel)  are derived from the  JComponent  class </li></ul><ul><li>JFrame,  be...
Displaying graphics in frames – panels <ul><li>Frames are containers – they can contain other user interface/graphical com...
Content  pane Frame JPanel SomeText JField
Panels <ul><li>Panels ( JPanel  class) are added to the content pane </li></ul><ul><li>Panels are themselves containers </...
Drawing on panels <ul><li>The  paintComponent()  method in  JComponent  (a superclass of  JPanel ) must be overridden </li...
<ul><li>The following code creates a class  MyPanel  into which graphics can be drawn </li></ul>class MyPanel extends JPan...
<ul><li>The  Graphics  object defines the graphics context (fonts, line styles, colours etc) </li></ul><ul><li>A call to  ...
Displaying text in graphics windows <ul><li>Text can be drawn onto panels using the  Graphics.drawString()  method </li></...
import javax.swing.*; import java.awt.*; public  class MyPanel extends JPanel { public void paintComponent(Graphics g) {  ...
import java.awt.event.*; import javax.swing.*; import java.awt.*; public class HelloFrame extends JFrame { public HelloFra...
public class FrameTest { public static void main(String[] args) { JFrame frame=new HelloFrame(); frame.show(); } }
 
<ul><li>Text fonts can be set/reset </li></ul><ul><ul><li>The existing font applies until it is reset </li></ul></ul><ul><...
 
Drawing simple graphics <ul><li>Class  java.awt.Graphics  contains methods which allow simple graphics to be drawn in diff...
<ul><li>Examples of different shapes </li></ul><ul><ul><li>Graphics.drawLine(int x1, int y1, int x2, int y2)  draws a stra...
class DrawPanel extends JPanel { public void paintComponent(Graphics g) {   super.paintComponent(g);   g.setColor(Color.re...
 
Displaying images <ul><li>We can read images stored in GIF and JPEG formats and draw the image onto a graphics panel using...
Normal program thread Load image from file Create new thread Image loading thread Program waits to be informed when image ...
<ul><li>Image read from file by a  Toolkit  object </li></ul><ul><ul><li>getDefaultToolkit()  returns the default toolkit ...
import java.awt.*; import java.awt.event.*; import javax.swing.*; class ImagePanel extends JPanel { public ImagePanel() { ...
 
And finally …. <ul><li>Swing/AWT are massive and complex </li></ul><ul><ul><li>We have only scratched the surface </li></u...
“ 640K ought to be enough for anybody.” --Bill Gates, 1981
Nu inschrijven voor het schaaktoernooi
Upcoming SlideShare
Loading in...5
×

M C6java5

707

Published on

Published in: Technology, Business
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
707
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
4
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Transcript of "M C6java5"

  1. 1. Simple Control Structures boolean s, the if statement switch-case
  2. 2. What are control structures? <ul><li>You can’t do very much if your program consists of just a list of commands to be done in order </li></ul><ul><ul><li>The program cannot choose whether or not to perform a command </li></ul></ul><ul><ul><li>The program cannot perform the same command more than once </li></ul></ul><ul><ul><li>Such programs are extremely limited! </li></ul></ul><ul><li>Control structures allow a program to base its behavior on the values of variables </li></ul>
  3. 3. boolean <ul><li>boolean is one of the eight primitive types </li></ul><ul><ul><li>boolean s are used to make yes/no decisions </li></ul></ul><ul><ul><li>All control structures use booleans </li></ul></ul><ul><li>There are exactly two boolean values, true (“yes”) and false (“no”) </li></ul><ul><ul><li>boolean , true , and false are all lowercase </li></ul></ul><ul><li>boolean s are named after George Boole, the founder of Boolean logic </li></ul>
  4. 4. Declaring boolean variables <ul><li>boolean variables are declared like any other kind of variable: </li></ul><ul><ul><li>boolean hungry; </li></ul></ul><ul><ul><li>boolean passingGrade; </li></ul></ul><ul><ul><li>boolean taskCompleted = false; </li></ul></ul><ul><li>boolean values can be assigned to boolean variables: </li></ul><ul><ul><li>taskCompleted = true; </li></ul></ul>
  5. 5. Numeric comparisons <ul><li>The following numeric comparisons each give a boolean result: </li></ul><ul><ul><li>x < y // is x less than y? </li></ul></ul><ul><ul><li>x <= y // is x less than or equal to y? </li></ul></ul><ul><ul><li>x == y // is x equal to y? (do not use =) </li></ul></ul><ul><ul><li>x != y // is x unequal to y? </li></ul></ul><ul><ul><li>x >= y // is x greater than or equal to y? </li></ul></ul><ul><ul><li>x > y // is x greater than y? </li></ul></ul><ul><li>Reminder: Don’t use == or != for floating-point numbers </li></ul>
  6. 6. The if statement <ul><li>The if statement has the form: </li></ul><ul><ul><li>if ( boolean-expression ) statement </li></ul></ul><ul><li>Examples: </li></ul><ul><ul><li>if (passingGrade) System.out.println(&quot;Whew!&quot;); </li></ul></ul><ul><ul><li>if (x > largest) largest = x; </li></ul></ul><ul><ul><li>if (citBook.price < 40.00) citBook.purchase(); </li></ul></ul><ul><li>The if statement controls one other statement </li></ul><ul><ul><li>Often this isn’t enough; we want to control a group of statements </li></ul></ul>
  7. 7. Compound statements <ul><li>We can use braces to group together several statements into one “compound” statement: </li></ul><ul><ul><li>{ statement ; statement ; ...; statement ; } </li></ul></ul><ul><li>Braces can group any number of statements: </li></ul><ul><ul><li>{ } // OK--this is an “empty” statement </li></ul></ul><ul><ul><li>{ x = 0; } // OK--braces don’t hurt </li></ul></ul><ul><ul><li>{ temp = x; x = y; y = temp; } //typical use </li></ul></ul><ul><li>The compound statement is the only kind of statement that does not end with a semicolon </li></ul>
  8. 8. The if statement again <ul><li>The if statement controls one other statement, but it can be a compound statement </li></ul><ul><li>Example: </li></ul><ul><ul><li>if (cost < amountInPocket) { System.out.println(&quot;Spending $&quot; + cost); amountInPocket = amountInPocket - cost; } </li></ul></ul><ul><li>It’s good style to use braces even if the if statement controls only a single statement: </li></ul><ul><ul><li>if (cost > amountInPocket) { System.out.println(&quot;You can't afford it!&quot;); } </li></ul></ul><ul><li>I personally make an exception to this style rule when the controlled statement fits easily on the same line with the if : </li></ul><ul><ul><li>if (x < 0) x = -x; // use absolute value of x </li></ul></ul>
  9. 9. Flowchart for the if statement condition? statement true false
  10. 10. The if-else statement <ul><li>The if-else statement chooses which of two statements to execute </li></ul><ul><li>The if-else statement has the form: </li></ul><ul><ul><li>if ( condition ) statement-to-execute-if-true ; else statement-to-execute-if-false ; </li></ul></ul><ul><li>Either statement (or both) may be a compound statement </li></ul><ul><li>Notice the semicolon after each controlled statement </li></ul>
  11. 11. Example if-else statements <ul><li>if (x >= 0) absX = x; else absX = -x; </li></ul><ul><li>if (itemCost <= bankBalance) { writeCheck(itemCost); bankBalance = bankBalance - itemCost; } else { callHome(); askForMoreMoney(2 * itemCost); } </li></ul>
  12. 12. Flowchart for the if-else statement condition? true statement-1 statement-2 false
  13. 13. Aside: the “mod” operator <ul><li>The modulo, or “mod,” operator returns the remainder of an integer division </li></ul><ul><li>The symbol for this operation is % </li></ul><ul><li>Examples: </li></ul><ul><ul><li>57 % 10 gives 7 </li></ul></ul><ul><ul><li>20 % 6 gives 2 </li></ul></ul><ul><li>Useful rule: x is divisible by y if x % y == 0 </li></ul><ul><li>If the left operand is negative, the result is negative (or zero) </li></ul><ul><ul><li>Examples: -20 % 3 = -2 , 20 % -3 = 2 , -20 % -3 = -2 </li></ul></ul>
  14. 14. Nesting if (or if-then ) statements <ul><li>A year is a leap year if it is divisible by 4 but not by 100, unless it is also divisible by 400 </li></ul><ul><li>if (year % 4 == 0) { if (year % 100 == 0) { if (year % 400 == 0) leapYear = true; else leapYear = false; } else leapYear = true; } else leapYear = false; </li></ul>
  15. 15. Operations on boolean s <ul><li>Assume p and q are booleans </li></ul><ul><li>There are four basic operations on booleans: </li></ul><ul><ul><li>Negation (“not”): !p is true if p is false (and false otherwise) </li></ul></ul><ul><ul><li>Conjunction (“and”): p && q is true if both p and q are true </li></ul></ul><ul><ul><li>Disjunction (“or”): p || q is true if either of p and q is true </li></ul></ul><ul><ul><li>Exclusive or (“xor”): p ^ q is true if just one of p and q is true </li></ul></ul>
  16. 16. Simpler tests <ul><li>A simpler leap-year test: </li></ul><ul><ul><li>if (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) leapYear = true; else leapYear = false; </li></ul></ul><ul><li>An even simpler leap-year test: </li></ul><ul><ul><li>leapYear = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0); </li></ul></ul>
  17. 17. The if-else statement <ul><li>The if-else statement chooses which of two statements to execute </li></ul><ul><li>The if-else statement has the form: </li></ul><ul><ul><li>if ( condition ) statement-to-execute-if-true ; else statement-to-execute-if-false ; </li></ul></ul><ul><li>Either statement (or both) may be a compound statement </li></ul><ul><li>Notice the semicolon after each statement </li></ul><ul><li>The else part is optional </li></ul>
  18. 18. Dangling Else <ul><li>Compiler cannot determine which “if” an “else” belongs to if there are no braces </li></ul><ul><ul><li>String password = Keyboard.readString(); </li></ul></ul><ul><ul><li>if (password.equals (realPassword)) </li></ul></ul><ul><ul><li>if (name.equals (“admin”)) </li></ul></ul><ul><li>loggedIn = superPrivileges = true; </li></ul><ul><li>else </li></ul><ul><li>System.out.println (“Error”); </li></ul><ul><li>Java matches else with last unfinished if </li></ul><ul><li>Moral: Use shortcuts at your own risk – or don’t ! </li></ul>
  19. 19. Multiway selection <ul><li>Multiple conditions, each of which causes a different block of statements to execute </li></ul><ul><li>Can be used where there are more than 2 options </li></ul><ul><ul><li>if ( condition1 ) </li></ul></ul><ul><ul><li>{ </li></ul></ul><ul><ul><li>statements … </li></ul></ul><ul><ul><li>} </li></ul></ul><ul><ul><li>else </li></ul></ul><ul><ul><li>{ </li></ul></ul><ul><ul><li>if ( condition2 ) </li></ul></ul><ul><ul><li>{ </li></ul></ul><ul><ul><li>statements … </li></ul></ul><ul><ul><li>} </li></ul></ul><ul><ul><li>else </li></ul></ul><ul><ul><li>… </li></ul></ul><ul><ul><li>} </li></ul></ul>
  20. 20. “ if” ladder <ul><li>Just a nicer way to write multiway selection </li></ul><ul><li>if (operation == ‘a’) </li></ul><ul><li>{ </li></ul><ul><li>answer = first + second; </li></ul><ul><li>} </li></ul><ul><li>else if (operation == ‘s’) </li></ul><ul><li>{ </li></ul><ul><li>answer = first – second; </li></ul><ul><li>} </li></ul><ul><li>else if (operation == ‘m’) </li></ul><ul><li>{ </li></ul><ul><li>answer = first * second; </li></ul><ul><li>} </li></ul>
  21. 21. The “switch” statement <ul><li>Selects among different statements based on a single integer or character expression </li></ul><ul><li>Each set of statements starts in “case” and ends in “break” because switch does not use {}s </li></ul><ul><ul><li>break passes control to statement immediately after switch </li></ul></ul><ul><li>“ default” applies if none of the cases match </li></ul>
  22. 22. Sample switch statement <ul><li>switch (SouperSandwichOrder) </li></ul><ul><li>{ </li></ul><ul><li>case 1 : cheese = 1; </li></ul><ul><li>break; </li></ul><ul><li>case 2 : cheese = 1; </li></ul><ul><li>tomato = 1; </li></ul><ul><li>break; </li></ul><ul><li>case 3 : cheese = 1; </li></ul><ul><li>tomato = 1; </li></ul><ul><li>chukka = 1; </li></ul><ul><li>break; </li></ul><ul><li>default : cheese = 1; </li></ul><ul><li>break; </li></ul><ul><li>} </li></ul>
  23. 23. “ break” optimisation <ul><li>If break is omitted, control continues to next statement in the switch </li></ul><ul><li>switch (SouperSandwichOrder) </li></ul><ul><li>{ </li></ul><ul><li>case 3 : chukka = 1; </li></ul><ul><li>case 2 : tomato = 1; </li></ul><ul><li>case 1 : </li></ul><ul><li>default : cheese = 1; </li></ul><ul><li>} </li></ul>
  24. 24. Characters in “switch” <ul><li>char Operation = Keyboard.readChar (“What to do?”); </li></ul><ul><li>switch (Operation) </li></ul><ul><li>{ </li></ul><ul><li>case ‘a’ : answer = a + b; </li></ul><ul><li>break; </li></ul><ul><li>case ‘s’ : answer = a – b; </li></ul><ul><li>break; </li></ul><ul><li>case ‘m’ : answer = a * b; </li></ul><ul><li>break; </li></ul><ul><li>case ‘d’ : if (b != 0) </li></ul><ul><li>{ </li></ul><ul><li>answer = a / b; </li></ul><ul><li>break; </li></ul><ul><li>} </li></ul><ul><li>default : answer = 0; </li></ul><ul><li>System.out.println (“Error”); </li></ul><ul><li>break; </li></ul><ul><li>} </li></ul>
  25. 25. Boolean operators ! || && Java true if parameter is false; false if parameter is true; NOT true if at least one parameter is true OR true if both parameters are true AND Meaning Boolean Algebra
  26. 26. Operator precedence <ul><li>Now that we have seen how operators can be mixed, we need precedence rules for all operators </li></ul><ul><ul><li>() (highest precedence – performed first) </li></ul></ul><ul><ul><li>! </li></ul></ul><ul><ul><li>* / % </li></ul></ul><ul><ul><li>+ - </li></ul></ul><ul><ul><li>< <= > >= </li></ul></ul><ul><ul><li>== != </li></ul></ul><ul><ul><li>&& </li></ul></ul><ul><ul><li>|| </li></ul></ul><ul><ul><li>= (lowest precedence – performed last) </li></ul></ul>
  27. 27. Reversing expressions <ul><li>Use ! operator to reverse meaning of boolean expression, e.g., </li></ul><ul><ul><li>if (mark >= 0) </li></ul></ul><ul><ul><li>{ </li></ul></ul><ul><ul><li>// do nothing </li></ul></ul><ul><ul><li>} </li></ul></ul><ul><ul><li>else </li></ul></ul><ul><ul><li>System.out.println (“Error”); </li></ul></ul><ul><li>Instead, invert the condition </li></ul><ul><ul><li>if (! (mark >= 0)) </li></ul></ul><ul><ul><li>System.out.println (“Error”); </li></ul></ul><ul><li>Can we do better ? </li></ul>
  28. 28. Afvinkopdracht 5: Tic-tac-toe
  29. 29. Graphic programming The GUI revisited
  30. 30. <ul><li>Java, unlike C & C++, has standard packages for graphics </li></ul><ul><li>2 related packages and sub-packages support graphics in Java </li></ul><ul><ul><li>java.awt ( A bstract W indows T oolkit) </li></ul></ul><ul><ul><li>javax.swing </li></ul></ul><ul><li>AWT is ‘peer-based’ </li></ul><ul><ul><li>Depends on graphical elements native local platform’s graphics system </li></ul></ul><ul><ul><li>Unix/Windows graphical programs written using AWT will have a different ‘look and feel’ </li></ul></ul>
  31. 31. <ul><li>Swing is much more platform independent </li></ul><ul><ul><li>Graphical components are pre-built and are simply painted onto windows </li></ul></ul><ul><ul><li>Relies less on the underlying runtime environment </li></ul></ul><ul><ul><li>Usually slower than AWT-based programs </li></ul></ul><ul><li>In practice graphical programs are a mixture of Swing and AWT classes </li></ul><ul><ul><li>AWT takes care of all of the event handling for GUI’s (see later) </li></ul></ul>
  32. 32. Frames <ul><li>A frame is a top level window which is a container for graphical components (canvas, buttons, menus etc) </li></ul><ul><li>The AWT has a Frame class and Swing has a JFrame class </li></ul><ul><li>The following program displays an empty frame </li></ul>
  33. 33. import javax.swing.*; class MyFrame extends JFrame { public MyFrame() { setTitle(&quot;My first graphics program&quot;); setSize(400,300); } } public class FrameTest { public static void main(String[] args) { JFrame frame=new MyFrame(); frame.show(); } }
  34. 35. <ul><li>A class MyFrame is defined which is a sub-class of JFrame </li></ul><ul><ul><li>A title is added </li></ul></ul><ul><ul><li>The frame is sized to 400x300 (by default, a frame is 0x0) </li></ul></ul><ul><li>The frame is created by a call to the constructor </li></ul><ul><li>The frame is displayed by a call to JFrame.show() </li></ul><ul><ul><li>This creates a separate thread which runs until the program is terminated – the main thread terminates </li></ul></ul>
  35. 36. Swing inheritance hierarchy <ul><li>The JFrame class inherits attributes from higher level container classes </li></ul><ul><ul><li>Typically for resizing and positioning frames </li></ul></ul><ul><li>Class names beginning with ‘J’ are Swing classes – everything else is part of AWT </li></ul>
  36. 37. JFrame JComponent JPanel … .. Component Frame Window Container
  37. 38. <ul><li>Most swing components (for example JPanel) are derived from the JComponent class </li></ul><ul><li>JFrame, being a top level window, is derived from the Window class </li></ul><ul><li>Other top level windows include JApplet and JDialog </li></ul>
  38. 39. Displaying graphics in frames – panels <ul><li>Frames are containers – they can contain other user interface/graphical components </li></ul><ul><li>A frame contains a content pane into which components can be added </li></ul><ul><li>The following code is typical </li></ul>Container contentPane=frame.getContentPane(); Component c= ….; // UI or graphical component contentPane.add (c); // Add to the frame
  39. 40. Content pane Frame JPanel SomeText JField
  40. 41. Panels <ul><li>Panels ( JPanel class) are added to the content pane </li></ul><ul><li>Panels are themselves containers </li></ul><ul><ul><li>The can contain other UI components </li></ul></ul><ul><ul><li>They also have a surface onto which graphics can be drawn </li></ul></ul><ul><ul><ul><li>Text </li></ul></ul></ul><ul><ul><ul><li>Basic shapes (lines, boxes etc) </li></ul></ul></ul><ul><ul><ul><li>Images </li></ul></ul></ul>
  41. 42. Drawing on panels <ul><li>The paintComponent() method in JComponent (a superclass of JPanel ) must be overridden </li></ul><ul><li>paintComponent() is called automatically when the window has to be drawn or redrawn – for example when it is moved by the user. It is also called when the repaint() method of a panel is called </li></ul>
  42. 43. <ul><li>The following code creates a class MyPanel into which graphics can be drawn </li></ul>class MyPanel extends JPanel { public void paintComponent(Graphics g) { super.paintComponent(g); // Code placed here to draw graphics } }
  43. 44. <ul><li>The Graphics object defines the graphics context (fonts, line styles, colours etc) </li></ul><ul><li>A call to super.paintComponent() calls the paintComponent() method in JComponent (the base class of JPanel ) </li></ul><ul><ul><li>This call sets up the graphics context and performs other complex tasks </li></ul></ul>
  44. 45. Displaying text in graphics windows <ul><li>Text can be drawn onto panels using the Graphics.drawString() method </li></ul><ul><li>The text font and size can be optionally set/reset </li></ul><ul><li>The following program draws a string onto a panel </li></ul><ul><ul><li>The panel is then added to a frame which is then displayed using JFrame.show() </li></ul></ul>
  45. 46. import javax.swing.*; import java.awt.*; public class MyPanel extends JPanel { public void paintComponent(Graphics g) { super.paintComponent(g); g.drawString(&quot;Hello there!&quot;,150,125); } }
  46. 47. import java.awt.event.*; import javax.swing.*; import java.awt.*; public class HelloFrame extends JFrame { public HelloFrame() { setTitle(&quot;Drawing a string example&quot;); setSize(400,300); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); Container contentPane=getContentPane(); contentPane.add(new MyPanel()); } }
  47. 48. public class FrameTest { public static void main(String[] args) { JFrame frame=new HelloFrame(); frame.show(); } }
  48. 50. <ul><li>Text fonts can be set/reset </li></ul><ul><ul><li>The existing font applies until it is reset </li></ul></ul><ul><li>The following code sets a bold Helvetica font with a larger font size </li></ul>public class MyPanel extends JPanel { public void paintComponent(Graphics g) { super.paintComponent(g); Font f=new Font(“Helvetica”,Font.BOLD,25); g.setFont(f); g.drawString(&quot;Hello there!&quot;,150,125); } }
  49. 52. Drawing simple graphics <ul><li>Class java.awt.Graphics contains methods which allow simple graphics to be drawn in different colours </li></ul><ul><li>Graphics.setcolor() sets the drawing colour </li></ul><ul><ul><li>Colour is represented by the class java.awt.Color(int red, int blue, int green) defining the RGB components </li></ul></ul><ul><ul><li>Preset constants exist (defined as static constants in Color) </li></ul></ul><ul><ul><ul><li>Color.red </li></ul></ul></ul><ul><ul><ul><li>Color.orange </li></ul></ul></ul><ul><ul><ul><li>Color.pink </li></ul></ul></ul><ul><ul><ul><li>etc </li></ul></ul></ul>
  50. 53. <ul><li>Examples of different shapes </li></ul><ul><ul><li>Graphics.drawLine(int x1, int y1, int x2, int y2) draws a straight line from (x1,y1) to (x2,y2) </li></ul></ul><ul><ul><li>Graphics.drawRect(int x, int y, int w, int h) draws a rectangle from upper left hand corner (x,y) with width w and height h </li></ul></ul><ul><ul><li>Graphics.drawOval(int x, int y, int w, int h) draws an outline of an ellipse with a ‘bounding rectangle’ as above </li></ul></ul><ul><ul><li>Graphics.drawPolygon(int[] xc, int[] yc, int n) draws a polygon with n vertices with the co-ordinates being stored in arrays xc and yc </li></ul></ul><ul><ul><li>Graphics.fillOval (int x, int y, int w, int h) fills the oval with the current draw colour </li></ul></ul>
  51. 54. class DrawPanel extends JPanel { public void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(Color.red); g.drawRect(20,30,50,50); g.setColor(Color.green); g.drawOval(100,30,90,60); g.fillOval(100,30,90,60); g.setColor(Color.yellow); int[] xcoords={180,200,250,275,225}; int[] ycoords={170,130,130,150,200}; g.drawPolygon(xcoords,ycoords,5); g.fillPolygon(xcoords,ycoords,5); } }
  52. 56. Displaying images <ul><li>We can read images stored in GIF and JPEG formats and draw the image onto a graphics panel using Graphics.drawImage() </li></ul><ul><li>When an image is read from file, a new thread of execution is started in parallel </li></ul><ul><ul><li>Usually, the program needs to wait until the image is loaded </li></ul></ul><ul><ul><li>Loaded images need to be ‘tracked’ and the program informed when the loading is complete </li></ul></ul>
  53. 57. Normal program thread Load image from file Create new thread Image loading thread Program waits to be informed when image loaded Image loading complete – send signal Normal program thread resumes
  54. 58. <ul><li>Image read from file by a Toolkit object </li></ul><ul><ul><li>getDefaultToolkit() returns the default toolkit </li></ul></ul><ul><ul><li>getDefaultToolkit().getImage(filename) reads the jpg or gif file containing the image </li></ul></ul><ul><li>An image is added to a tracker object which sends a signal back to the panel when the loading is complete </li></ul><ul><li>The try/catch statements are for exception handling – causes the program to wait for the image to be loaded (see later) </li></ul><ul><li>Following program draws an image into a panel </li></ul>
  55. 59. import java.awt.*; import java.awt.event.*; import javax.swing.*; class ImagePanel extends JPanel { public ImagePanel() { image = Toolkit.getDefaultToolkit().getImage( “Pisa.jpg” ); MediaTracker tracker=new MediaTracker(this); tracker.addImage(image,0); try {tracker.waitForID(0);} catch (InterruptedException e){} } public void paintComponent(Graphics g) { super.paintComponent(g); g.drawImage(image,0,0,this); } private Image image; }
  56. 61. And finally …. <ul><li>Swing/AWT are massive and complex </li></ul><ul><ul><li>We have only scratched the surface </li></ul></ul><ul><li>Typically Java API’s have been built on top of Swing </li></ul><ul><ul><li>Java2D </li></ul></ul><ul><ul><li>Java3D </li></ul></ul><ul><li>In practice, you would use these to do real work for example involving image processing or 3D rendering </li></ul>
  57. 62. “ 640K ought to be enough for anybody.” --Bill Gates, 1981
  58. 63. Nu inschrijven voor het schaaktoernooi
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×