Question

Modify the JavaFX TipCalculator application program to allow the user to enter the number of persons...

Modify the JavaFX TipCalculator application program to allow the user to enter the number of persons in the party through a text field. Calculate and display the amount owed by each person in the party if the bill is to be split evenly among the party members.

///////////

TipCalculatorController.java:

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.NumberFormat;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.control.Slider;
import javafx.scene.control.TextField;

public class TipCalculatorController
{
// formatters for currency and percentages
private static final NumberFormat currency =
NumberFormat.getCurrencyInstance();
private static final NumberFormat percent =
NumberFormat.getPercentInstance();

private BigDecimal tipPercentage = new BigDecimal(0.15); // 15% default

// GUI controls defined in FXML and used by the controller's code
@FXML
private TextField amountTextField;

@FXML
private Label tipPercentageLabel;

@FXML
private Slider tipPercentageSlider;

@FXML
private TextField tipTextField;

@FXML
private TextField totalTextField;

// calculates and displays the tip and total amounts
@FXML
private void calculateButtonPressed(ActionEvent event)
{
try
{
BigDecimal amount = new BigDecimal(amountTextField.getText());
BigDecimal tip = amount.multiply(tipPercentage);
BigDecimal total = amount.add(tip);

tipTextField.setText(currency.format(tip));
totalTextField.setText(currency.format(total));
}
catch (NumberFormatException ex)
{
amountTextField.setText("Enter amount");
amountTextField.selectAll();
amountTextField.requestFocus();
}
}

// called by FXMLLoader to initialize the controller
public void initialize()
{
// 0-4 rounds down, 5-9 rounds up
currency.setRoundingMode(RoundingMode.HALF_UP);
  
// listener for changes to tipPercentageSlider's value
tipPercentageSlider.valueProperty().addListener(
new ChangeListener<Number>()
{
@Override
public void changed(ObservableValue<? extends Number> ov,
Number oldValue, Number newValue)
{
tipPercentage =
BigDecimal.valueOf(newValue.intValue() / 100.0);
tipPercentageLabel.setText(percent.format(tipPercentage));
}
}
);
}
}

/////////////////////

TipCalculator.java:

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class TipCalculator extends Application
{
@Override
public void start(Stage stage) throws Exception
{
Parent root =
FXMLLoader.load(getClass().getResource("TipCalculator.fxml"));

Scene scene = new Scene(root); // attach scene graph to scene
stage.setTitle("Tip Calculator"); // displayed in window's title bar
stage.setScene(scene); // attach scene to stage
stage.show(); // display the stage
}

public static void main(String[] args)
{
// create a TipCalculator object and call its start method
launch(args);
}
}
/////////////////////////

TipCalculator.fxml:

<?xml version="1.0" encoding="UTF-8"?>

<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.geometry.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>

<GridPane alignment="TOP_LEFT" hgap="8.0" vgap="0.0" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/2.2" fx:controller="TipCalculatorController">
<children>
<Label text="Amount" textAlignment="RIGHT" GridPane.columnIndex="0" GridPane.rowIndex="0" />
<Label fx:id="tipPercentageLabel" text="15%" textAlignment="RIGHT" GridPane.columnIndex="0" GridPane.rowIndex="1" />
<Label text="Tip" textAlignment="RIGHT" GridPane.columnIndex="0" GridPane.rowIndex="2" />
<Label text="Total" textAlignment="RIGHT" GridPane.columnIndex="0" GridPane.rowIndex="3" />
<TextField id="amountTextBox" fx:id="amountTextField" prefWidth="-1.0" GridPane.columnIndex="1" GridPane.rowIndex="0" />
<Slider fx:id="tipPercentageSlider" blockIncrement="5.0" majorTickUnit="1.0" max="30.0" minorTickCount="1" showTickLabels="false" showTickMarks="false" snapToTicks="true" value="15.0" GridPane.columnIndex="1" GridPane.rowIndex="1" />
<TextField fx:id="tipTextField" editable="false" focusTraversable="false" prefWidth="-1.0" GridPane.columnIndex="1" GridPane.rowIndex="2" />
<TextField fx:id="totalTextField" editable="false" focusTraversable="false" prefWidth="-1.0" GridPane.columnIndex="1" GridPane.rowIndex="3" />
<Button id="calculateButton" maxWidth="1.7976931348623157E308" mnemonicParsing="false" onAction="#calculateButtonPressed" text="Calculate" GridPane.columnIndex="1" GridPane.rowIndex="4" />
</children>
<columnConstraints>
<ColumnConstraints halignment="RIGHT" hgrow="SOMETIMES" minWidth="10.0" prefWidth="-1.0" />
<ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="-1.0" />
</columnConstraints>
<padding>
<Insets bottom="14.0" left="14.0" right="14.0" top="14.0" />
</padding>
<rowConstraints>
<RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
<RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
<RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
<RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
<RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
</rowConstraints>
</GridPane>

0 0
Add a comment Improve this question Transcribed image text
Answer #1

If you have any problem with the code feel free to comment. I haven't included the main file as it remains the same

Controller

package tipCalculator;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.NumberFormat;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.control.Slider;
import javafx.scene.control.TextField;

public class TipCalculatorController {
// formatters for currency and percentages
   private static final NumberFormat currency = NumberFormat.getCurrencyInstance();
   private static final NumberFormat percent = NumberFormat.getPercentInstance();

   private BigDecimal tipPercentage = new BigDecimal(0.15); // 15% default

// GUI controls defined in FXML and used by the controller's code
   @FXML
   private TextField amountTextField;

   @FXML
   private Label tipPercentageLabel;

   @FXML
   private Slider tipPercentageSlider;

   @FXML
   private TextField tipTextField;

   @FXML
   private TextField totalTextField;
  
@FXML
private TextField noOfPersonTextfield;

@FXML
private TextField perCostTextfield;

// calculates and displays the tip and total amounts
   @FXML
   private void calculateButtonPressed(ActionEvent event) {
       try {
           BigDecimal amount = new BigDecimal(amountTextField.getText());
           //taking number of persons
           BigDecimal numberOfPerson = new BigDecimal(noOfPersonTextfield.getText());
           BigDecimal tip = amount.multiply(tipPercentage);
           BigDecimal total = amount.add(tip);
           BigDecimal perPerson = total.divide(numberOfPerson);
          
          
           tipTextField.setText(currency.format(tip));
           totalTextField.setText(currency.format(total));
           perCostTextfield.setText(currency.format(perPerson));//setting the cost per person
       } catch (NumberFormatException ex) {
           amountTextField.setText("Enter amount");
           amountTextField.selectAll();
           amountTextField.requestFocus();
       }
   }

// called by FXMLLoader to initialize the controller
   public void initialize() {
// 0-4 rounds down, 5-9 rounds up
       currency.setRoundingMode(RoundingMode.HALF_UP);

// listener for changes to tipPercentageSlider's value
       tipPercentageSlider.valueProperty().addListener(new ChangeListener<Number>() {
           @Override
           public void changed(ObservableValue<? extends Number> ov, Number oldValue, Number newValue) {
               tipPercentage = BigDecimal.valueOf(newValue.intValue() / 100.0);
               tipPercentageLabel.setText(percent.format(tipPercentage));
           }
       });
   }
}

FXML

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.geometry.Insets?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.Slider?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.ColumnConstraints?>
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.layout.RowConstraints?>

<GridPane alignment="TOP_LEFT" hgap="8.0" vgap="0.0" xmlns="http://javafx.com/javafx/11.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="tipCalculator.TipCalculatorController">
   <children>
       <Label text="Amount" textAlignment="RIGHT" GridPane.columnIndex="0" GridPane.rowIndex="0" />
<Label text="Cost per person" GridPane.rowIndex="5" />
<Label text="Number of person" GridPane.rowIndex="1" />
       <Label fx:id="tipPercentageLabel" text="15%" textAlignment="RIGHT" GridPane.columnIndex="0" GridPane.rowIndex="2" />
       <Label text="Tip" textAlignment="RIGHT" GridPane.columnIndex="0" GridPane.rowIndex="3" />
       <Label text="Total" textAlignment="RIGHT" GridPane.columnIndex="0" GridPane.rowIndex="4" />
       <TextField id="amountTextBox" fx:id="amountTextField" prefWidth="-1.0" GridPane.columnIndex="1" GridPane.rowIndex="0" />
       <Slider fx:id="tipPercentageSlider" blockIncrement="5.0" majorTickUnit="1.0" max="30.0" minorTickCount="1" showTickLabels="false" showTickMarks="false" snapToTicks="true" value="15.0" GridPane.columnIndex="1" GridPane.rowIndex="2" />
       <TextField fx:id="tipTextField" editable="false" focusTraversable="false" prefWidth="-1.0" GridPane.columnIndex="1" GridPane.rowIndex="3" />
       <TextField fx:id="totalTextField" editable="false" focusTraversable="false" prefWidth="-1.0" GridPane.columnIndex="1" GridPane.rowIndex="4" />
       <Button id="calculateButton" maxWidth="1.7976931348623157E308" mnemonicParsing="false" onAction="#calculateButtonPressed" text="Calculate" GridPane.columnIndex="1" GridPane.rowIndex="6" />
<TextField fx:id="noOfPersonTextfield" GridPane.columnIndex="1" GridPane.rowIndex="1" />
<TextField fx:id="perCostTextfield" editable="false" GridPane.columnIndex="1" GridPane.rowIndex="5" />
   </children>
   <columnConstraints>
       <ColumnConstraints halignment="RIGHT" hgrow="SOMETIMES" minWidth="10.0" prefWidth="-1.0" />
       <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="-1.0" />
   </columnConstraints>
   <padding>
       <Insets bottom="14.0" left="14.0" right="14.0" top="14.0" />
   </padding>
   <rowConstraints>
       <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
<RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
       <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
       <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
       <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
<RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
       <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
   </rowConstraints>
</GridPane>

Output

Add a comment
Know the answer?
Add Answer to:
Modify the JavaFX TipCalculator application program to allow the user to enter the number of persons...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Java Programming Assignment (JavaFX required). You will modify the SudokuCheckApplication program that is listed below. Start...

    Java Programming Assignment (JavaFX required). You will modify the SudokuCheckApplication program that is listed below. Start with the bolded comment section in the code below. Create a class that will take string input and process it as a multidimensional array You will modify the program to use a multi-dimensional array to check the input text. SudokuCheckApplication.java import javafx.application.*; import javafx.event.*; import javafx.geometry.*; import javafx.scene.*; import javafx.scene.control.*; import javafx.scene.layout.*; import javafx.stage.*; public class SudokuCheckApplication extends Application { public void start(Stage primaryStage)...

  • please help me debug this Create a Future Value Calculator that displays error messages in labels.GUISpecificationsStart...

    please help me debug this Create a Future Value Calculator that displays error messages in labels.GUISpecificationsStart with the JavaFX version of the Future Value application presented in chapter 17. Create error message labels for each text field that accepts user input. Use the Validation class from chapter 17 to validate user input.Format the application so that the controls don’t change position when error messages are displayed. package murach.business; public class Calculation {        public static final int MONTHS_IN_YEAR =...

  • For this question you will need to complete the methods to create a JavaFX GUI application...

    For this question you will need to complete the methods to create a JavaFX GUI application that implements two String analysis algorithms. Each algorithm is activated when its associated button is pressed. They both take their input from the text typed by the user in a TextField and they both display their output via a Text component at the bottom of the GUI, which is initialized to “Choose a string methods as indicated in the partially completed class shown after...

  • JavaFX! Just need to fill several lanes of code please!!! CSE205 OOP and Data Structure Quiz #15 Last Name (print) First Name (print) Write a JavaFX GUI application program that simulates a timer. T...

    JavaFX! Just need to fill several lanes of code please!!! CSE205 OOP and Data Structure Quiz #15 Last Name (print) First Name (print) Write a JavaFX GUI application program that simulates a timer. The timer should show "count: the beginning and increase the number by 1 in every one second, and so on. o" at .3 A Timer - × A Timer Count: 0 Count: 1 (B) After 1 second, the GUI Window (A) Initial GUI Window According to the...

  • Can someone please comment this on what the javafx do and how they are implemented? import...

    Can someone please comment this on what the javafx do and how they are implemented? import javafx.application.Application; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.layout.GridPane; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.scene.paint.Paint; import javafx.scene.text.Font; import javafx.scene.text.FontWeight; import javafx.scene.text.Text; import javafx.stage.Stage; public class TextPanel extends Application { GridPane grid = null; Text scenetitle = null; Label tDrawLabel = null; Label bsc345Label = null; HBox THBox = null; VBox mVBox = new VBox(2); Stage primaryStage = null; @Override public void start(Stage...

  • You may adjust the code as you want. Thank you! CODING HERE: import javafx.application.Application; import javafx.event.*;...

    You may adjust the code as you want. Thank you! CODING HERE: import javafx.application.Application; import javafx.event.*; import javafx.scene.*; import javafx.scene.control.*; import javafx.scene.layout.*; import javafx.stage.*; import javafx.geometry.*; public class OrderSystem extends Application implements EventHandler<ActionEvent> { // Attributes for GUI private Stage stage; // The entire window, including title bar and borders private Scene scene; // Interior of window private BorderPane layout; // Add four labels private Label itemLabel = new Label("Item Name:"); private Label numberLabel = new Label("Number:"); private Label costLabel...

  • Please Help, JavaFX assignment. This assignment will focus on the use anonymous inner class handlers to...

    Please Help, JavaFX assignment. This assignment will focus on the use anonymous inner class handlers to implement event handling. Assignment 12 Assignment 12 Submission Follow the directions below to submit Assignment 12: This assignment will be a modification of the Assignment 11 program. This program should use the controls and layouts from the previous assignment. No controls or layouts should be added or removed for this assignment. Add event handlers for the three buttons. The event handlers should be implemented...

  • Java: In this assignment, you will create an accumulator accumulator-calculator that displays a sad face “...

    Java: In this assignment, you will create an accumulator accumulator-calculator that displays a sad face “ :-( “ whenever the number displayed by the calculator is negative and a happy face “ :-) ” whenever the number displayed is positive. The calculator responds to the following commands: num + , num - , num * , num / and C ( Clear ). After initial run, if the user clicks 8 and then presses the “+” button for example, the...

  • In this practice program you are going to practice creating graphical user interface controls and placing...

    In this practice program you are going to practice creating graphical user interface controls and placing them on a form. You are given a working NetBeans project shell to start that works with a given Invoice object that keeps track of a product name, quantity of the product to be ordered and the cost of each item. You will then create the necessary controls to extract the user input and display the results of the invoice. If you have any...

  • This is my code. I need the UML for this code My code: public class Main...

    This is my code. I need the UML for this code My code: public class Main extends FlightManager {    Stage window;    Scene scene;    Button button;    HBox layout = new HBox(20);    Label dateTxt, airlineTxt, originTxt, destTxt, clssTxt, scopeTxt, adultsTxt, childTxt;    @Override public void start(Stage stage) { // create the UI and show it here    window = stage; window.setTitle("Reservations 2020"); button = new Button("New Flight");    VBox group3 = new VBox(10); dateTxt = Text("", group3);...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT