These directions are written specifically to help you add a button to the ArrayStats.java program for CS 1 lab 7. This does make for a nice description for how to add graphical Buttons in Java in general, though. Also note that there are descriptions of how to work with buttons and with other graphical user interface (GUI) objects in the course textbooks.
Button
in Java is just another object. It's just like the very common String
objects that you've seen before. Just because a Button
object happens to have a graphical representation doesn't mean it doesn't behave like any other object. Each one is represented by a variable, and we have to declare it (say what type our variable is), initialize it (give it a value), and the object then stores some data and has some methods available for us to use.
ArrayStats.java
file:bClear
. I'm going to name my Button
variable bStdDev just so I'll have something to refer to. So, my line would then look like:
Applet
this will happen inside the init() method. This is a method that gets called once when the Applet
is first created and started. That's exactly what we want for our own initialization.Button
variables being initialized. Just like with any other object, we have to call the new keyword variable, and then we call the constructor method for this type of object.String
object needs to take in the line of text characters, a string literal, which it will represent. Similarly, we see that each Button
constructor method also takes in a string literal. This is the text that will be displayed on the surface of the graphical button. Remember that the button we're creating requires the text: "Standard Deviation".
Button
object. It would probably make the most sense to add this right under the last button initialization line (for the variable bClear
).Button
declared and initialized, we now have 2 things left to do that are specific to these GUI objects: (1) set up a listener and (2) add the GUI object to something that can display it.addActionListener()
method works like any other method you may call: it takes in parameters and it then performs some action. Here this method takes in a single parameter, which is the object where we have code that we want to respond to clicks on this button. We're using the this key word to say that we want this particular object to repond to button clicks. (Yes, ArrayStats.java will be forming an object, just like you have String
objects and Button
objects. Don't worry about this. For now just think of it as referencing "this file of code.")if
statement corresponding to each of the different buttons. Now we'll just add another if
statement for our button and within the code body for that if
statement we'll call our stdDev()
method. Here's a code example for how to do that:if (cause == bStdDev) { int[] temp = new int[nextFree]; for(int i=0; i<temp.length; i++){ temp[i] = (int) list[i]; } mAnswer.setText("The standard deviation is " + stdDev(temp)); }