Programmierpraktikum Claudius Gros, SS2012 Institut für theoretische Physik Goethe-University Frankfurt a.m. 1 of 18 17/01/13 11:46
Java Applets 2 of 18 17/01/13 11:46
Java applets embedding Java applications into webpages simulations, tutorials, web interfaces applet example copy Java code to file AppletDrawingLines.java run the Java compiler javac AppletDrawingLines copy html code to file anything.html open the html file with a browser firefox anything.html, sometimes you need a reload 1. 2. 3. import javax.swing.*; // for JApplet,.. import java.awt.*; // for Color import java.util.*; // for sleeping 4. 5. /** Java applet example based on Japplet. 3 of 18 17/01/13 11:46
6. 7. 8. * Has no main() function, init() executed before paint(). public class AppletDrawingLines extends JApplet { 9. 10. 11. 12. 13. 14. 15. 16. 17. int width, height; public void init() { width = getsize().width; height = getsize().height; setbackground(color.black); // size of the html applet box // executed when the applet starts // getsize() is a member function of JApplet // returning the size of the html applet box 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. /** The.pain() function is executed whenever the applet is * asked to redraw itself. public void paint(graphics g) { g.setcolor(color.green); for (int i=0; i<10; i++) { g.drawline(width, height, i * width / 10, 0); // drawline(x-start,y-start,x-end,y-end) try { 28. Thread.sleep(700); // sleep for a short time 4 of 18 17/01/13 11:46
29. 30. 31. 32. 33. 34. catch (InterruptedException e) { System.out.println(e.toString()); // end of loop over drawing lines // end of AppletDrawingLines.paint() // end of AppletDrawingLines html code for embedding applet html tags are like brackets: <center>...</center> <html> <head> <meta charset="utf8" /> <title>java applets</title> </head> <!-- this is a comment: a html page has a header and a body --> <body> <center> <h1>embedded Java applet</hr> <br><br> <applet width=400 height=400 code="appletdrawinglines.class"> </applet> </center> </body> </html> 5 of 18 17/01/13 11:46
Mouse events here Applet instead of JApplet and java.awt instead of javax.swing the interfaces MouseListener and MouseMotionListener are implemented, all their member functions need to be explicitly declared, even when void 1. 2. 3. import java.applet.*; // this example with Applet instead of JApplet import java.awt.*; import java.awt.event.*; 4. 5. 6. public class AppletMouseFollow extends Applet implements MouseListener, MouseMotionListener { 7. 8. 9. 10. int width, height; // size of html applet box int mx, my; // the mouse coordinates boolean isbuttonpressed = false; 11. 12. public void init() { 6 of 18 17/01/13 11:46
13. 14. 15. width = getsize().width; height = getsize().height; setbackground(color.black); 16. 17. 18. mx = width/2; // starting position of my = height/2; // square 19. 20. 21. 22. addmouselistener( this ); // adding event listeners addmousemotionlistener( this ); 23. 24. 25. 26. 27. 28. 29. 30. 31. 32. 33. 34. 35. /** Called when the pointer enters the applet's box. * All functions of the implemented interfaces * MouseListener and MouseMotionListener need to be implemented. public void mouseentered( MouseEvent e ) { setbackground(color.blue); public void mouseexited( MouseEvent e ) { setbackground(color.orange); /** Called after a press and release of a mouse button * with no motion in between. 7 of 18 17/01/13 11:46
36. 37. 38. 39. 40. 41. 42. 43. 44. 45. 46. 47. 48. 49. 50. 51. 52. 53. 54. 55. 56. 57. 58. * If the user presses, drags, and then releases, * there will be no click event generated. public void mouseclicked( MouseEvent e ) { setbackground(color.cyan); /** Called when mouse down but not released. public void mousepressed( MouseEvent e ) { isbuttonpressed = true; setbackground(color.gray); repaint(); // re // "Consume" the event so it won't be processed in the // default manner by the source which generated it. e.consume(); /** Called when released after drag. public void mousereleased( MouseEvent e ) { isbuttonpressed = false; setbackground(color.black); repaint(); e.consume(); 8 of 18 17/01/13 11:46
59. 60. 61. 62. 63. 64. 65. 66. 67. 68. 69. 70. 71. 72. 73. 74. 75. 76. 77. /** Called during motion when no buttons are down. public void mousemoved( MouseEvent e ) { mx = e.getx(); // the mouse events provides the current my = e.gety(); // mouse position showstatus( "Mouse at (" + mx + "," + my + ")" ); // browser status line repaint(); // calls the paint() method e.consume(); /** Called during motion with buttons down. public void mousedragged( MouseEvent e ) { mx = e.getx(); my = e.gety(); showstatus( "Mouse at (" + mx + "," + my + ")" ); repaint(); e.consume(); 78. 79. 80. 81. public void paint( Graphics g ) { if (isbuttonpressed) g.setcolor(color.black); // black rectangle if moused down 9 of 18 17/01/13 11:46
82. 83. else g.setcolor(color.gray); // gray otherwise 84. // 85. g.fillrect(mx-20, my-20, 40, 40); // filled and centered rectangle 86. 87. // end of AppletMouseFollow 10 of 18 17/01/13 11:46
Bouncing with and without threads try to to change speed while bouncing double buffering for professional applications, avoiding flickering: paint first everything offscreen and then upload full graphics (not done here) 1. 2. 3. import java.awt.*; import java.awt.event.*; import java.applet.applet; 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. /** A class can extend only a single parent class * but it can implement any number of interfaces. public class AppletBounce extends Applet implements ActionListener, AdjustmentListener, Runnable { private int width, height; // width, height of applet box private int tick = 100; // length of pausini, speed control private int initialy = 70; // bouncing between these 11 of 18 17/01/13 11:46
14. private int lowesty; // two values 15. 16. private Button gothreaded = new Button("go threaded"); 17. 18. 19. private Button gonotthreaded = new Button("go not threaded"); private Scrollbar speed = new Scrollbar(Scrollbar.HORIZONTAL,tick,30,20,400); 20. 21. 22. 23. 24. /** Called when applet is loaded. public void init() { setbackground(new Color(230,230,230)); 25. width = getsize().width; 26. 27. 28. 29. height = getsize().height; lowesty = (int)(height*0.8); // --- select layout manager // use relative units 30. setlayout(new BorderLayout()); // a layout manger 31. 32. Panel buttons = new Panel(); // a seperate panel for the buttons 33. 34. 35. 36. // --- button for starting animation with current thread gonotthreaded.setbackground(color.lightgray); gonotthreaded.addactionlistener(this); buttons.add(gonotthreaded); 12 of 18 17/01/13 11:46
37. 38. 39. 40. 41. 42. // --- button for starting animation in an additional thread gothreaded.setbackground(color.lightgray); gothreaded.addactionlistener(this); buttons.add(gothreaded); add("north", buttons); // add both bottoms to the top 43. 44. 45. 46. 47. 48. 49. 50. 51. // --- the Scrollbar 'speed' is inside the Panel 'speedcontrol' Panel speedcontrol = new Panel(); speedcontrol.setbackground(color.lightgray); speed.setpreferredsize(new Dimension((int)(width*0.6),20)); speedcontrol.add(new Label("faster",Label.RIGHT)); speedcontrol.add(speed); speed.addadjustmentlistener(this); speedcontrol.add(new Label("slower")); 52. 53. add("south", speedcontrol); // add the speed-control bar to the bottom 54. // end of AppletBounce.init() 55. 56. 57. 58. 59. /** Catch scrollbar event. public void adjustmentvaluechanged(adjustmentevent e) { tick = speed.getvalue(); 13 of 18 17/01/13 11:46
60. 61. 62. 63. 64. 65. 66. /** Catch button events. public void actionperformed(actionevent e) { if (e.getsource() == gothreaded) // the new Thread calls run() new Thread(this).start(); // running the object 'this' 67. if (e.getsource() == gonotthreaded) // calling directly 68. doanimation(); // doanimation() 69. 70. 71. 72. 73. 74. 75. 76. /** AppletBounce is implementing runnable and run() is * called when a new thread is started. public void run() { doanimation(); 77. 78. 79. 80. 81. 82. /** Let a ball at random position x bounce downwards * and upwards, with increasing speed (step). public void doanimation() { // --- setup of bounds 14 of 18 17/01/13 11:46
83. 84. 85. 86. 87. int minx = (int)(width*0.1); // allways use int maxx = (int)(width*0.9); // relative units int x = (int)(minx+math.random()*(maxx-minx)); // fixed random x for bouncing int y = initialy; // variable y of bouncing int step = 1; // (in)decrement for y 88. 89. 90. 91. 92. 93. 94. // --- setup of graphics Graphics g = getgraphics(); Color background = getbackground(); // needed for repainting g.setcolor(color.black); g.drawline(minx, lowesty+20, // bottom line maxx, lowesty+20); 95. 96. 97. 98. 99. 100. 101. 102. 103. 104. 105. // --- bouncing downwards while (y <= lowesty) { g.filloval(x, y, 20, 20); // paint ball pause(tick); // pause animation method g.setcolor(background); g.filloval(x, y, 20, 20); // turn ball to background g.setcolor(color.black); y = y+step; step++; 15 of 18 17/01/13 11:46
106. 107. 108. 109. 110. 111. 112. 113. 114. // --- hitting bottom g.setcolor(new Color(204,51,51)); g.filloval(x, lowesty, 20, 15); // extra image for lowest point g.drawstring("boing!",x-10,lowesty+35); // its 'boing' pause(tick*3); // pause for reading g.setcolor(background); g.drawstring("boing!",x-10,lowesty+35); g.filloval(x, lowesty, 20, 15); // erase the extra squeeze ball 115. 116. 117. 118. 119. 120. 121. 122. 123. 124. 125. 126. 127. // --- bouncing upwards g.setcolor(color.black); while (step>0) { step--; y = y-step; g.filloval(x, y, 20, 20); pause(tick); g.setcolor(background); g.filloval(x, y, 20, 20); g.setcolor(color.black); // end of AppletBounce.doAnimation() 128. 16 of 18 17/01/13 11:46
129. /** Just a wrapper for the exception capture. 130. 131. 132. 133. 134. private void pause(int pauselength) { try { Thread.sleep(pauseLength); catch (InterruptedException e) { // end of AppletBounce 17 of 18 17/01/13 11:46
What to do with applets? physics / science simulations - visualization 1D quantum wave packet scattering one / two player collision game Conway's Game of Life... interaction web-based GUI (graphical user interface) web-based user-user interactions (maps, chat, mail,...) browser games 18 of 18 17/01/13 11:46