We've got a jFrame with a 6 buttons at the top, one for each homework assignment. Each button uses the same event, the event just checks to see which text is on the button to determine what to do.
Now, for example, when the user clicks HW3 it'll display a message telling them some instructions. Then they click the HW3 button again & it'll take the values and do some calculations.
I can get that to work fine, but I also need a message that tells the user to enter values if they leave them empty. I can't get this to work because the values are empty to start with so it bypasses my 'instructions' message and skips straight to the message telling them that the fields are empty.
I'm not sure how to get this working right. Any ideas? The code is below.
Thanks!
if ("HW3".equals(actionCommand)) {
msg = "Please enter the required data in the fields to the left. Then click the 'HW3' button again.\n"
+ "\n'P' = Price per gallon."
+ "\n'M' = Miles per gallong."
+ "\n'D' = Distance traveled.";
jTextField1.setVisible(true);
jTextField2.setVisible(true);
jTextField3.setVisible(true);
jLabel1.setText("P:");
jLabel2.setText("M:");
jLabel3.setText("D:");
double gasPrice, miGal, distance;
double tankSize = 16;
String gPStr, mGStr, diStr;
gPStr = jTextField1.getText();
mGStr = jTextField2.getText();
diStr = jTextField3.getText();
if(gPStr.trim().length() != 0 && mGStr.trim().length() != 0 && diStr.trim().length() != 0){
gasPrice = Double.parseDouble(gPStr);
miGal = Double.parseDouble(mGStr);
distance = Double.parseDouble(diStr);
Hw3Car myCar = new Hw3Car(miGal);
myCar.setFuelLevel(tankSize);
myCar.drive(distance);
msg = (myCar.getFuelLevel() < 0.1)? // getter / shorthand If statement - if FuelLevel is less than 0.1
"You ran out of gas." : // you ran out of gas
"The amount of gas left in the tank is " + myCar.getFuelLevel() + "," // else builds the string displays your info
+ "\n" + " and you got " + myCar.truEff(gasPrice) + " miles per dollar.";
} else {
if(gPStr.trim().length() == 0 || mGStr.trim().length() == 0 || diStr.trim().length() == 0){
msg = "Please enter values in all fields!";
}
}
}


Sign In
Create Account



Back to top









