Question
I have to make a JavaFX application to calculate Miles Per Gallon. My button doesn't work and I also need check if I did the
I have to make a JavaFX application to calculate Miles Per Gallon. My button doesn't work and I also need check if I did the following correctly:
1. Align the GridPane at the top center of the scene. In addition, add 25 pixels of padding between the grid and the edges of the window, and add 10 pixels of space between the rows and columns in the grid.
2. Find the event handler for the button and notice that it uses an anonymous class. Change the handle() method for this class so it gets the values from the miles and gallons text fields, calculates the miles per gallon, and then displays it in the read-only text field.
Here is my code so far:
import javafx.application.Application; import javafx.geometry.HPos; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.scene.layout.GridPane; import javafx.stage.Stage;
public class MPGApplication extends Application{ TextField milesT = new TextField(), gallonsT = new TextField(), mpgT = new TextField(); Button calculateB = new Button("Calculate");
@Override public void start(Stage primaryStage) { GridPane p = new GridPane(); Label milesL, gallonsL, mpgL; milesL = new Label("Miles:"); gallonsL = new Label("Gallons:"); mpgL = new Label("MPG"); p.add(milesL, 0, 0); p.add(milesT,1, 0); p.add(gallonsL, 0,1); p.add(gallonsT,1,1); p.add(mpgL,0,2); p.add(mpgT, 1, 2);
p.add(calculateB,0,3); GridPane.setHalignment(calculateB, HPos.RIGHT); p.setPadding(new Insets(12,12,12,12)); p.setAlignment(Pos.CENTER); p.setHgap(10); p.setVgap(10);
Scene scene = new Scene(p, 400, 400); primaryStage.setTitle("MPG Calculator"); primaryStage.setScene(scene); primaryStage.show(); } private void calculateMPG() { String milesStr; milesStr = milesT.getText(); String gallonsStr; gallonsStr = gallonsT.getText(); double miles = Double.valueOf(milesStr); double gallons = Double.valueOf(gallonsStr); double mpg = miles/gallons; mpgT.setText(String.valueOf(mpg)); } }
Miles Per Gallon Calculator Miles: 300 Gallons: 12.5 MPG:24 Calculate
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started