0
我有一個程序,我試圖在JavaFX中使用事件處理程序來使按鈕執行某些操作,例如標有Exit的按鈕以結束程序。我認爲我的代碼是正確的,但它不起作用。想知道該怎麼做?下面的代碼:Java中的事件處理程序
import edu.seminolestate.studentanalysis.ActionEvent;
import edu.seminolestate.studentanalysis.EventHandler;
import javafx.application.Application;
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.BorderPane;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
public class ProcessPayrollApplication extends Application {
HourlyEmployee hE = new HourlyEmployee(newName, hoursWorked, hourlyRate);
@Override
public void start(Stage primaryStage) throws Exception {
Label lblName = new Label("Employee name: ");
Label lblHours = new Label("Hours worked: ");
Label lblHourlyPay = new Label("Hourly pay rate: ");
Label lblGrossPay = new Label("Gross pay:" + hE.computeGrossPay());
Label lblTaxes = new Label("Taxes: " + hE.computeTaxAmount());
Label lblNetPay = new Label("Net pay: " + hE.computeNetPay());
TextField txtName = new TextField();
TextField txtHours = new TextField();
TextField txtPay = new TextField();
Button btnCalculate = new Button ("Calculate");
Button btnClear = new Button ("Clear");
Button btnExit = new Button ("Exit");
BorderPane bp = new BorderPane();
GridPane gp = new GridPane();
gp.setVgap(15);
gp.setHgap(15);
FlowPane fp = new FlowPane();
fp.setHgap(10);
fp.setAlignment(Pos.CENTER);
gp.add(lblName, 0, 0);
gp.add(lblHours, 0, 1);
gp.add(lblHourlyPay, 0, 2);
gp.add(lblGrossPay, 0, 3);
gp.add(lblTaxes, 0, 4);
gp.add(lblNetPay, 0, 5);
gp.add(txtName, 1, 0, 2, 1);
gp.add(txtHours, 1, 1, 2, 1);
gp.add(txtPay, 1, 2, 2, 1);
BorderPane.setAlignment(gp, Pos.CENTER);
bp.setCenter(gp);
BorderPane.setAlignment(fp, Pos.CENTER);
bp.setBottom(fp);
//Add event handlers
btnExit.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
System.exit(0);
}
});
Scene scene = new Scene(bp, 350, 250);
primaryStage.setScene(scene);
primaryStage.show();
primaryStage.setTitle("Payroll");
}
public static void main(String[] args) {
Application.launch(args);
}
}
您沒有將這些按鈕添加到場景中,您在啓動應用程序時是否看到這些按鈕?關於捕捉按鈕,請點擊您正在做的事! – Flood2d
@ Flood2d我將它們添加到添加到添加到場景中的BorderPane的FlowPane中。是不是可以做?編輯:等等,我沒有添加他們......我很密集。 – senpaimaster
沒關係,但是在您發佈的代碼中,我沒有看到將它們添加到FlowPane的位置,您創建它們,將偵聽器添加到btnExit,但不會將它們添加到FlowPane。如果你可以看到他們的圖形,也許你省略了代碼的一部分? – Flood2d