Programming 101
By Way of Java
Instructor: T. Boutell
Transcript for 11/7/96
Stimulants AnonymousWelcome to the Java programmers' roasteria. A wide variety of stimulating beverages are consumed among the whirring virtual machines.
You say, "last week we began to discuss an actual, living, breathing Java applet."
You say, "we had begun discussing the 'action' method when we ran out of time for the night."
You say, "so we're going to pick up again at that point."
You say, "please refer to the source code for the calculator example:"
You say, "http://boutell.com/~boutell/class/Calculator.java"
You say, "now, the first line of the action method is as follows:"
You say, "public boolean action(Event event, Action arg)"
You say, "we discussed this last week, but I'll briefly review:"
You say, "we are replacing the action method of the Applet class with our own version, suited to this applet."
You say, "the action method is called by java when a significant 'action' occurs, such as a button click."
You say, "the first argument to the action method contains an 'Event' object, which describes the circumstances surrounding the action."
You say, "the second argument is an 'Object' because its real type varies a lot from one kind of action to the next. It is a clumsy way of doing things and we are not going to look at it here."
You say, "now, the next line is where tonight's new material begins."
You say, "if (event.target == add) {"
You say, "the 'target' of an event is the component of the applet in which the event took place. In this case, it is the button which was clicked upon."
You say, "this is handy, because we set the variable 'add' to refer to that same button, when we created the button."
You say, "so now, we can compare the two to see if they refer to the same object."
You say, "if they do, we know the 'add' button was clicked upon."
You say, "any questions so far?"
jsam says, "might the add button send events for anything other than getting clicked?"
You say, "sam: other kinds of events, yes, but there are different methods that receive those. The 'action' method is fired when the button is 'fired' by the user, whether by the mouse or by the keyboard, etc."
jsam says, "right."
curtis says, "how does this scale when you have a whole lot of buttons? do you still centralize the event loop thusly?"
You say, "curtis: not necessarily. You could extend the Button class and provide an action method there that does something interesting right away and returns true to indicate that the action has been dealt with."
You say, "curtis: or you could extend the 'Panel' class, which can contain many components, write an interesting action method there, and add that Panel in turn to the applet."
curtis says, "hmm. if you do that, how does the Button get a reference to its applet? do you have to set that up manually?"
You say, "curtis: the Button learns 'who its friends are' when the 'add' method is used to add it to the applet that contains it. That happened in the 'init' method of the calculator."
curtis says, "right."
You say, "okay. Let's move on:"
You say, "addToCurrent();"
You say, "this line calls the 'addToCurrent()' method of the applet. We could have just plugged in all that code right here, but we would have had to do it in at least one other place, so we save typing and mistakes by writing a method for that work."
You say, "I'll discuss addToCurrent() in more detail when we get to it, but it adds the value in the text area to the running total."
You say, "next line:"
You say, "result.setText("");"
You say, "'result' is a variable we set earlier to refer to the TextField where the user inputs information."
You say, "the TextField class has a setText method, which can be used to set the current contents at any time."
You say, "here we use it to clear the text field, now that we've added the number there to the running total. This makes room for the next number the user will type in."
You say, "the next line:"
You say, "result.requestFocus();"
You say, "some of you are probably familiar with the idea of 'keyboard focus.' In most programs, one of the 'controls' on the screen is receiving most keyboard activity at any one time."
You say, "in Windows applications, for instance, you can 'cycle' the focus from one control to the next with the tab key."
You say, "when the user interacts with the calculator, they almost certainly want to type in one number after another, clicking on the plus button in between..."
You say, "so we want to make sure the text entry area keeps the attention of the keyboard at all times."
You say, "fortunately, the requestFocus method of the Component class, and anything such as a TextField which is descended from it, is provided as a way to explicitly give the focus to a particular component."
You say, "any questions at this point?"
Tom gobbles a few red hot blue chips.
You say, "okay..."
You say, "frequently in writing java programs, you will want to be able to express an idea like 'if this is true take this action, otherwise if this is true take this action, otherwise do this as a last resort,' or something similar."
You say, "the Java syntax for this, and I apologize to those for whom this is pretty old hat, is like so:"
You say, "if (a condition which is true or false) {"
You say, "some code goes here..."
You say, "} else if (another condition) {""
You say, "some more code for the second case..."
You say, "} else {"
You say, "some code for the last resort."
You say, "and of course a final }."
You say, "all of these clauses are optional, except the initial if of course."
You say, "Let's look at the second clause:"
You say, "else if (event.target == equals) {"
You say, "'if the user clicked on the equals button...'"
You say, "addToCurrent();"
You say, "'then add the value in the text field to the running total..."
You say, "String s = Float.toString(current);"
You say, "this line is not so familiar."
You say, "would anyone like to take a crack at interpreting it?"
Tom waits for Lisa Simpson.
bart has disconnected. (from jsam)
bart goes home. (from jsam)
jkcohen says, "This coerces the value of the floating point variable current to a string?"
You say, "jon: yes, exactly."
jkcohen says, "Why didn't we declare s up in the declarations section?"
You say, "jon: we can declare variables most anywhere. If we declare a variable inside a method, like this, then it exists only for the life of this call to the method."
You say, "jon: this variable is a scratchpad; it's not part of the essential description of a Calculator like the variables up top are."
jkcohen says, "Ah, minty-fresh Scope!"
You say, "the syntax looks a bit magical, so let me show you what the toString method of the Float class looks like..."
jkcohen says, "OK."
You say, "okay. Here's what the toString method looks like in its declaration:"
You say, "class Float {"
You say, "... more stuff here of course..."
You say, "static public String toString(float f) { ... }"
You say, "}"
You say, "now, the 'static' keyword is new."
You say, "most methods can be thought of as 'verbs' which operate on the object we invoke them on."
You say, "static methods, though, are a bit different, because they don't have to be invoked on a specific object."
You say, "last week I explained that 'float' and 'Float' are different things: 'float' is a simple numeric variable for doing calculations quickly without creating true objects. 'Float' is a class containing a lot of useful methods that do stuff with numbers. 'toString' is one of those methods."
You say, "since we don't have a 'real' object of the Float class, the java designers saved us the trouble of creating one every time we want to convert a number to a user-friendly string of digits."
You say, "they did this by providing a static method which accepts a float. Yes, it would be more elegant if we could say 'current.toString()', but the distinction between 'real objects' and numeric variables is a fact of life in Java."
You say, "this stuff is a bit weird, and if you find it complicated, you can use it in a 'cookie cutter' way by writing down useful stuff like this line. You don't need to understand it perfectly."
You say, "the next line:"
You say, "result.setText(s);"
You say, "this is a lot like the first clause, so to be brief, we are now setting the text field to contain the string we just put together. The user can now see the result."
You say, "skipping ahead to the last clause:"
You say, "} else if (event.target == clear) {"
You say, "'if the clear button was clicked upon...'"
You say, "current = 0;"
You say, "'clear our running total...'"
You say, "result.setText("");"
You say, "'and clear the entry field too.'"
You say, "and skipping to the last line of the method:"
You say, "return true;"
You say, "when we return 'true' from the action method, we are telling Java that this action has been completely dealt with."
You say, "if we had returned 'false', java would have tried passing the action to the next outer container. This component happens to be the applet, though, so we're pretty much the outermost box."
You say, "OK, any questions before we move on?"
gwost says, "yep"
gwost says, "I'm not quite sure what "result.requestFocus();" is doing."
You say, "steve: the telnet window you're typing this into currently has the keyboard focus. This means that if you move the mouse anywhere on the screen, most keys you type will still go to the telnet window."
You say, "steve: calling the 'requestFocus' method on a particular component asks Java to give that keyboard focus to that component pronto."
You say, "steve: we're doing this after every button click because we're Pretty Sure the user is going to want to type a number now, as opposed to using the keyboard to control the buttons, etc."
gwost says, "okay"
Tom moves on to the last method in the applet. We're going much faster this week; a lot of the remaining hard questions did get asked last week, so that makes a lot of sense.
You say, "void addToCurrent() {"
stevi says, "no public this time?"
You say, "stevi: no, because this method is never used except by other methods of this class. We don't want any 'outside' classes to mess about with it."
You say, "stevi: we used it twice in the 'action' method; it isn't used anywhere else."
stevi nods.
Tom moves on to the next line...
You say, "String text = result.getText();"
You say, "this call to the getText method fetches a copy of what's in the text entry area as a String object and assigns it to a temporary variable."
You say, "Float value = Float.valueOf(text);"
You say, "this is similar to the Float.toString method call we looked at earlier."
You say, "here we are using another static method in the Float class, this time to convert a string to an object of the 'Float' class."
You say, "I should note how we're calling this method. Since it is static, we don't have to invoke it on an existing object. But we do have to specify its name well enough to distinguish it from some other method..."
You say, "so we preface it with the name of the class: Float.valueOf"
You say, "now, as it happens, this method returns an object of the Float class, instead of just a simple float value."
You say, "the next line demonstrates why we don't use Float objects all the time:"
You say, "current += value.floatValue();"
You say, "we have to ask the Float object for the simple number associated with it by calling the floatValue method. Then we can do actual math and add it to our running total in 'current'."
You say, "writing 'foo.floatValue()' all over the place would get bothersome quick. Fortunately, we don't need it much except to convert strings to numbers and so on."
You say, "well, that's the complete applet..."
You say, "now would be a Good Time to ask Questions about anything that's bothering you, as we've come up to our first assignment, which is to turn this applet into a complete four-function calculator."
stevi asks for a clarification of what 'void' means.
You say, "stevi: a lot of methods return a value of some sort, whether it's a simple boolean 'true' or 'false', or a float, or a String object, or what have you..."
You say, "stevi: if a method *doesn't* return anything, it is said to return void."
stevi says, "ahh."
You say, "stevi: void methods are used much like verbs, in that you can just write 'addToCurrent(); on a line to call it. Other methods are more like functions such as 'cos' and 'sin' and so forth; they are often on the right hand side of an assignment with =."
You say, "stevi: you can also call a method that *does* return something 'like a verb'; if you do that, the return value just gets ignored."
stevi says, "so addToCurrent as a piece of code doesn't do anything; but when you call it, then it can act."
You say, "stevi: yes. All methods are like that, but the other methods in this class get called by code within java itself (within the web browser, etc). addToCurrent is different because it's not a replacement for a standard method like 'action'. We invented it."
jkcohen says, "So we need to make this calculator subtract, multiply and divide?"
You say, "jon: yes. Add those three functions, and see if you can deal with any weird, unexpected things you encounter when using your calculator."
You say, "jon: the 'look and feel' of a calculator is actually a bit less simple than I first thought."
You say, "if you feel like it, you can try adding 'memory' buttons as well."
jkcohen says, "Do you think we'll need a stack for this?"
You say, "jon: I don't think so, not a real stack."
You say, "jon: one problem is that calling addToCurrent when the '=' key is hit won't suffice anymore. You'll have to remember what the most recent operation was."
You say, "now, because we have time and we need to cover it at some point, I'm going to touch on how to put an applet into a web page properly..."
You say, "take a look at the HTML source to the http://boutell.com/~boutell/class/Calculator.html page."
You say, "<applet code="Calculator.class" width = 300 height = 32>"
You say, "the <applet> tag starts the embedding of a java applet. It *never* stands alone. There *must* be a closing </applet> tag. People screw that up all the time."
jkcohen says, "What would go between the two tags?"
You say, "the 'code' attribute to the applet tag should contain the URL of the main class of your applet -- the one we derived from java.applet.Applet. In this simple example we only have one class in any case."
You say, "the 'width' and 'height' attributes are also required. They specify the size of the applet in pixels. Applets *can't* resize themselves in the page so it is important to make these generous enough."
You say, "jon: two things can come between the opening and closing tags..."
You say, "jon: first the <param> tag, which looks like this:"
You say, "<param name="lines" value="20">"
You say, "'lines' and '20' are just made-up values in this case..."
You say, "you can have any number of <param> tags. Then, in your applet, when you want to look at the value of a parameter, you can say this:"
You say, "String s = getParameter("lines");"
You say, "that will fetch a String object containing '20' in this case."
You say, "getParameter is a method of the applet class, by the way."
You say, "There's one more issue surrounding applets in HTML pages:"
You say, "a lot of browsers don't dig java."
You say, "fortunately, all browsers are required to try to show tags that appear inside tags they don't understand."
You say, "browsers that *do* understand java ignore any tags inside the <applet>...</applet> pair except for <param>."
You say, "that means you can put a little message like 'Sorry, your browser can't handle Java, <a href="http://www.netscape.com/">Get Netscape Now</a>' before your closing </applet> tag."
You say, "that's about it for the <applet> tag. It is mercifully simple. In theory you can specify what language it's in, java or something else, but this doesn't come up much."
You say, "I can see that we've covered a lot of the basics, and you are for the most part ready to understand a lot of applet source code."
You say, "next week, we're going to cover exceptions, which are an important feature of the language we haven't touched on at all yet."
You say, "for tonight, we may as well call it a little early. I'll be glad to take questions, and I am extinguishing the 'No Wizardly Stuff' sign, so feel free to be as annoying as you like."
jkcohen says, "Tom, I think I understand the peculiarity I was whispering to you about."
You say, "shoot."
jkcohen says, "When I go 2+2=, I get 4."
jkcohen says, "But when I then try a successive operation, like +2, I get ten."
jkcohen says, "I believe the reason for this is that when I press the plus key, the first thing that happens is AddToCurrent();"
jkcohen says, "AddToCurrent() gets the text string from the result box, which is already 4, and it adds it to the floating value, which makes 8."
You say, "exactly."
jkcohen says, "Then, you press the 2 key and the = button, and that calls AddToCurrent, which faithfully adds 2, making 10."
Tom claps. Nice detective work.
jkcohen says, "Therefore, we might want to detach the equals operation from addition, as part of the generalization of our calculator."
jkcohen says, "Anyway, I can't think of the way to fix this right now, but that's what homework's for!"
jkcohen <- intellectual excitement.
Tom nods. "Here's a tip: it will be useful to remember which button was most recently used."
stevi notes this is the second time Tom's mentioned this. Perhaps this is Really Important.
Tom nods and prepares to close his log for this session.
Next | Up to the Index
Follow us on Twitter | Contact Us
Copyright 1994-2012 Boutell.Com, Inc. All Rights Reserved.
