Java – Serialization
The following example demonstrates how to make an applet respond to setup parameters specified in the document. This applet displays a checkerboard pattern of black and a second color.
The second color and the size of each square may be specified as parameters to the applet within the document.
CheckerApplet gets its parameters in the init() method. It may also get its parameters in the paint() method. However, getting the values and saving the settings once at the start of the applet, instead of at every refresh, is convenient and efficient.
The applet viewer or browser calls the init() method of each applet it runs. The viewer calls init() once, immediately after loading the applet. (Applet.init() is implemented to do nothing.) Override the default implementation to insert custom initialization code.
The Applet.getParameter() method fetches a parameter given the parameter’s name (the value of a parameter is always a string). If the value is numeric or other non-character data, the string must be parsed.
The following is a skeleton of Checker Applet java:
import java.applet.*; import java.awt.*; public class Checker Applet extends Applet { int squareSize = 50;// initialized to default size public void init () {} private void parseSquareSize (String param) {} private Color parseColor (String param) {} public void paint (Graphics g) {} } |
Here are Checker Applet’s init() and private parse Square Size() methods:
public void init () { String squareSizeParam = getParameter ("squareSize"); parseSquareSize (squareSizeParam); String colorParam = getParameter ("color"); Color fg = parseColor (colorParam); setBackground (Color.black); setForeground (fg); } private void parseSquareSize (String param) { if (param == null) return; try { squareSize = Integer.parseInt (param); } catch (Exception e) { // Let default value remain } } |
The applet calls parse Square Size() to parse the square Size parameter. parse Square Size() calls the library method Integer.parseInt(), which parses a string and returns an integer. Integer.parseInt() throws an exception whenever its argument is invalid.
Therefore, parseSquareSize() catches exceptions, rather than allowing the applet to fail on bad input.
The applet calls parse Color() to parse the color parameter into a Color value. parse Color() does a series of string comparisons to match the parameter value to the name of a predefined color. You need to implement these methods to make this applet works.
Related posts