Javafx:当我单击按钮时,如何对计算进行编码以获得结果?

Javafx:当我单击按钮时,如何对计算进行编码以获得结果?,javafx,Javafx,您应该使用eventListener或FXML。第二,我认为会更容易。需要榜样吗 更新:我添加了一个示例 Main.java Sample.fxml 是的,请提供一个例子 package javafx_tipcalc; import javafx.application.Application; import javafx.geometry.Insets; import javafx.geometry.Orientation; import javafx.geometry.Pos;

您应该使用eventListener或FXML。第二,我认为会更容易。需要榜样吗

更新:我添加了一个示例

Main.java

Sample.fxml


是的,请提供一个例子
 package javafx_tipcalc;

 import javafx.application.Application;
 import javafx.geometry.Insets;
 import javafx.geometry.Orientation;
 import javafx.geometry.Pos;
 import javafx.scene.Scene;
 import javafx.scene.control.Button;
 import javafx.scene.control.ChoiceBox;
 import javafx.scene.control.Label;
 import javafx.scene.control.Slider;
 import javafx.scene.control.TextField;
 import javafx.scene.layout.GridPane;
 import javafx.stage.Stage;
 import java.text.NumberFormat;


 public class JavaFX_TipCalc extends Application {

   // declare interface controls
// declare labels
Label titleLabel, checkAmtLabel, tipPercentLabel, splitLabel;
Label tipAmtLabel, totalLabel, amtPerPersonLabel;
// declare text fields
TextField checkAmtText, tipAmtText, totalText, amtPerPersonText;
// declare a slider
Slider tipPercentSlider;
// declare a choice box
ChoiceBox splitChoiceBox;
// declare a button
Button calcTipButton;
// declare currency and percent formatter
NumberFormat currency = NumberFormat.getCurrencyInstance();
NumberFormat persent = NumberFormat.getCurrencyInstance();
// declare a grid pane (8 rows and 2 columns)
GridPane grid;


@Override
public void start(Stage primaryStage) {

     // instantiate labels and their properties
    titleLabel = new Label("Tip Calculator");
    titleLabel.setMaxWidth(Double.MAX_VALUE);
    titleLabel.setAlignment(Pos.CENTER);
    checkAmtLabel = new Label("Check Amount");
    checkAmtLabel.setMaxWidth(Double.MAX_VALUE);
    checkAmtLabel.setAlignment(Pos.CENTER_RIGHT);
    tipPercentLabel = new Label("Tip Percent: 15%");
    tipPercentLabel.setMaxWidth(Double.MAX_VALUE);
    tipPercentLabel.setAlignment(Pos.CENTER_RIGHT);
    splitLabel = new Label("Split");
    splitLabel.setMaxWidth(Double.MAX_VALUE);
    splitLabel.setAlignment(Pos.CENTER_RIGHT);
    tipAmtLabel = new Label("Tip Amount");
    tipAmtLabel.setMaxWidth(Double.MAX_VALUE);
    tipAmtLabel.setAlignment(Pos.CENTER_RIGHT);
    totalLabel = new Label("Total");
    totalLabel.setMaxWidth(Double.MAX_VALUE);
    totalLabel.setAlignment(Pos.CENTER_RIGHT);
    amtPerPersonLabel = new Label("Amount per Person");
    amtPerPersonLabel.setMaxWidth(Double.MAX_VALUE);
    amtPerPersonLabel.setAlignment(Pos.CENTER_RIGHT);

    // instantiate text fileds and their properties
    double textFieldWidth = 100;
    checkAmtText = new TextField();
    checkAmtText.setOnMouseClicked(e -> ResetFields());
    checkAmtText.setPrefWidth(textFieldWidth);
   checkAmtText.setAlignment(Pos.CENTER_RIGHT);
    tipAmtText = new TextField();
    tipAmtText.setFocusTraversable(false);
   tipAmtText.setPrefWidth(textFieldWidth);
   tipAmtText.setAlignment(Pos.CENTER_RIGHT);
   tipAmtText.setEditable(false);
    totalText = new TextField();
    totalText.setFocusTraversable(false);
   totalText.setPrefWidth(textFieldWidth);
   totalText.setAlignment(Pos.CENTER_RIGHT);
   totalText.setEditable(false);
    amtPerPersonText = new TextField();
    amtPerPersonText.setFocusTraversable(false);
   amtPerPersonText.setPrefWidth(textFieldWidth);
   amtPerPersonText.setAlignment(Pos.CENTER_RIGHT);
   amtPerPersonText.setEditable(false);

    // instantiate a slider and its properties 
    tipPercentSlider = new Slider();
    tipPercentSlider.setPrefWidth(10);
    tipPercentSlider = new javafx.scene.control.Slider();
    tipPercentSlider.setPrefWidth(150);
    tipPercentSlider.setMin(0);
    tipPercentSlider.setMax(25);
    tipPercentSlider.setMajorTickUnit(5);
    tipPercentSlider.setMinorTickCount(1);        
    tipPercentSlider.setBlockIncrement(1);
    tipPercentSlider.setShowTickLabels(true);
    tipPercentSlider.setShowTickMarks(true);
    tipPercentSlider.setSnapToTicks(true);
    tipPercentSlider.setValue(15);
    tipPercentSlider.setOrientation(Orientation.HORIZONTAL);
    tipPercentSlider.valueProperty().addListener(
    (observable, oldvalue, newvalue) ->
    {           
      tipPercentLabel.setText(String.format("Tip Percent: 
     %2d%s",newvalue.intValue(),"%"));
    } );

    // instantiate a choice box and its properties
    splitChoiceBox = new ChoiceBox();
    splitChoiceBox.getItems().addAll("1 Way", "2 Ways", "3 Ways", "4 
    Ways", "5 Ways");
    splitChoiceBox.setValue("1 Way");

    splitChoiceBox.setPrefWidth(150);

    // instantiate a button and its properties
    calcTipButton = new Button("Calculate Tip");
    calcTipButton.setMaxWidth(Double.MAX_VALUE);
    calcTipButton.setOnAction(e -> CalcButtonClick()) ;

    // instantiate a grid pane and its properties
    grid = new GridPane();
    grid.setHgap(10);
    grid.setVgap(10);
    grid.setPadding(new Insets(10));
    grid.add(titleLabel, 0, 0, 2, 1);
    grid.addRow(1, checkAmtLabel, checkAmtText);
    grid.addRow(2, tipPercentLabel, tipPercentSlider);
    grid.addRow(3, splitLabel, splitChoiceBox);
    grid.add(calcTipButton, 0, 4, 2, 1);
    grid.addRow(5, tipAmtLabel, tipAmtText);
    grid.addRow(6, totalLabel, totalText);
    grid.addRow(7, amtPerPersonLabel, amtPerPersonText);

    // instantiate the grid pane and put items in in grid

   Scene scene = new Scene(grid);
   scene.getRoot().setStyle("-fx-font: 20 'Comic Sans MS'"); 


   primaryStage.setTitle("Tip Calculator");
   primaryStage.setScene(scene);
   primaryStage.show();


  }

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {

    launch(args);
 }

 private void CalcButtonClick() {
    /*
    Get the check amount from checkAmtText
    Get the tip percent from the slider
    Get the split the choice box

    Tip amount = check amount * tip percent
    Total amount = check amount + tip amount
    Amount per person = total amount / split

    Print the tip amount in tipAmtText
    Print the total amount in total Text
    Print the split amtPerPerson Text

    */
    double tipAmnt, checkAmnt, tipPercent,
            totalAmnt, AmntPerPerson;

            tipAmnt = Double.parseDouble(tipAmtText.getText());
            AmntPerPerson = 
            Double.parseDouble(amtPerPersonText.getText());
            checkAmnt = Double.parseDouble(checkAmtText.getText());
            totalAmnt = Double.parseDouble(totalText.getText());
            tipPercent = Double.parseDouble(tipPercentLabel.getText());



            tipAmnt = checkAmnt * tipPercent;
            totalAmnt = checkAmnt + tipAmnt;

            tipAmtText.setText(currency.format(tipAmnt));
            totalText.setText(currency.format(totalAmnt));






       }

    private void ResetFields() {
    /*
    Clear the check amount
    Clear the tip amount
    Clear the total amount
    Clear the amount per person
    Set the tip percent slider to 15%
    Set the split choice box to “1 Way”

    */ 

  }
 }
package application;

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

public class Main extends Application {
    @Override
    public void start(Stage primaryStage) {
        try {
            FXMLLoader fxmlLoader = new FXMLLoader();
            fxmlLoader.setLocation((getClass().getResource("Sample.fxml")));
            Parent panel = fxmlLoader.load();
            Scene scene = new Scene(panel, 300, 150);
            primaryStage.setTitle("Sum of two numbers");
            primaryStage.setScene(scene);
            primaryStage.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        launch(args);
    }
}
<?import javafx.geometry.*?>
<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>


<VBox maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="150.0" prefWidth="300.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.SampleController">
   <children>
      <AnchorPane prefHeight="55.0" prefWidth="300.0">
         <children>
            <HBox prefHeight="25.0" prefWidth="200.0" AnchorPane.leftAnchor="50.0" AnchorPane.rightAnchor="50.0">
               <children>
                  <Label text="x">
                     <HBox.margin>
                        <Insets left="31.0" />
                     </HBox.margin>
                  </Label>
                  <Label text="y">
                     <HBox.margin>
                        <Insets left="62.0" />
                     </HBox.margin>
                  </Label>
                  <Label text="z">
                     <HBox.margin>
                        <Insets left="62.0" />
                     </HBox.margin>
                  </Label>
               </children>
            </HBox>
            <HBox prefHeight="100.0" prefWidth="200.0" AnchorPane.bottomAnchor="20.0" AnchorPane.leftAnchor="50.0" AnchorPane.rightAnchor="50.0" AnchorPane.topAnchor="20.0">
               <children>
                  <TextField fx:id="xTextField" />
                  <TextField fx:id="yTextField" />
                  <TextField fx:id="zTextField" />
               </children>
            </HBox>
         </children>
      </AnchorPane>
      <AnchorPane prefHeight="200.0" prefWidth="200.0">
          <HBox AnchorPane.bottomAnchor="20.0" AnchorPane.leftAnchor="50.0" AnchorPane.rightAnchor="50.0" AnchorPane.topAnchor="20.0">
            <children>
                <Button mnemonicParsing="false" onAction="#sumIt" text="Sum it!" AnchorPane.bottomAnchor="20.0" AnchorPane.leftAnchor="50.0" AnchorPane.rightAnchor="50.0" AnchorPane.topAnchor="20.0" />
             </children>
             <children>
                <Button mnemonicParsing="false" onAction="#clearAll" text="Clear all!" AnchorPane.bottomAnchor="20.0" AnchorPane.leftAnchor="50.0" AnchorPane.rightAnchor="50.0" AnchorPane.topAnchor="20.0" />
             </children>
          </HBox>
      </AnchorPane>
   </children>
</VBox>
package application;

import javafx.fxml.FXML;
import javafx.scene.control.TextField;

public class SampleController {

    @FXML
    TextField xTextField, yTextField, zTextField;

    public void sumIt() {
        int sum;
        sum = Integer.parseInt(xTextField.getText()) + Integer.parseInt(yTextField.getText());
        zTextField.setText(Integer.toString(sum));
    }

    public void clearAll() {
        xTextField.setText("");
        yTextField.setText("");
        zTextField.setText("");
    }
}