Java Reference
In-Depth Information
In other words, by making the subclass execute the setExitButtonLocation method, the this.getWidth() and this.get
Height() statements will retrieve the subclass frame's width and height not the Useful-Frame's width and height.
Sorry, if this seems complicated, but it is. The good news is that, as you use superclasses and subclasses more
often, it will become easier and more familiar.
Now we need to have EmpFrame (a UsefulFrame subclass) invoke the setExitButtonLocation method.
5.
In EmpFrame, after the this .setBounds statement, add the following statement:
this .setExitButtonLocation();
We have to set the exit button's location after the setBounds statement because that statement resizes the frame
to 300 by 300. If we place it before the setBounds statement, the default size from UsefulFrame would be used to
calculate the location.
6.
Save the EmpFrame source code and run EmployeeApp.
Notice that the exit button now appears in the corner of the 300 by 300 frame.
7.
In the source code, change the size of the EmpFrame to 500 by 600, then save and run
EmployeeApp.
Notice the exit button is again placed in the lower-right-hand corner.
8. In EmpFrame, comment out the this .setBounds statement and save the source code.
Can you figure out what size the frame will be now? If not, run EmployeeApp and see.
The exit button is pretty cool but it doesn't do anything! (I guess it's not that cool after all.) However, like frames,
buttons can have listeners assigned to them. A button is tied to an action listener and, fortunately, an action listener
only requires one method.
Tutorial: Adding an Action Listener to a Button
The following steps (which should look very familiar) must be performed to enable an action listener:
1.
Import the ActionListener and ActionEvent classes
2.
Implement the action listener
3.
Code an actionPerformed method
4.
Add the action listener to the button
This time we will perform the steps in the order of 1, 3, 2, 4. This will prevent any error messages from being
generated as we enter the code. Why? When the implements keyword is entered (step 2), the syntax checker
automatically looks for the required import statements and actionPerformed method. Therefore, we will add these
statements (steps 1 and 3) before we insert the implements keyword (step 2).
1.
In ExitButton, add the following statements:
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
2.
After the ExitButton constructor, add the following:
public void actionPerformed(ActionEvent e){
}
 
Search WWH ::




Custom Search