Java Reference
In-Depth Information
17.
Move the setForeground statement before the setEmployeeProperties statement.
The actionPerformed method should look like the following:
public void actionPerformed(ActionEvent e) {
resultLbl.setForeground(Color.black);
this .setEmployeeProperties();
if (emp.getPayRate() != -1) {
if (dispBtn == e.getSource()) {
EmployeeFrame ef = new EmployeeFrame(emp);
} else {
if (grossBtn == e.getSource()) {
resultLbl.setText("Gross Salary is: " +
emp.grossSalaryCalcFormatted());
} else {
if (taxBtn == e.getSource()) {
resultLbl.setText("The Federal Tax amount is: "
+ emp.fedTaxCalcFormatted());
}
}
}
}
}
Now, isn't that a cleaner method? In addition, this method is much more efficient because we eliminated almost
all the method variables and all the duplicate Employee objects.
Tutorial: Throwing Exceptions
Up until now, we have only caught exceptions thrown by the system. Not only can your Java classes throw exceptions
but the messages can be customized. For instance, no employee can make less than $6.50 an hour, nor is there any
employee who can earn more than $35.00 an hour. The setter should check that the value supplied is within this
range, and if not, an exception should be thrown. We will throw an InvalidValue exception and customize the
message based on the invalid value.
After making this change to setPayRate, any method that uses the setPayRate method must be changed to check
for the exception. So, we will add try and catch blocks to the setEmployeeProperties method in EnterEmpInfo.
1.
In Employee, add the following import statement.
import org.omg.CORBA.DynAnyPackage.InvalidValue;
As usual, we must first import the class before we can use it.
Method headers must specify which exception(s) can be thrown. Exceptions are identified in the method header
with the throws keyword.
2.
Change the setPayRate method header to following:
public void setPayRate( double d) throws InvalidValue {
 
Search WWH ::




Custom Search