2017-04-24 82 views
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); 
    } 
} 
+0

您没有将这些按钮添加到场景中,您在启动应用程序时是否看到这些按钮?关于捕捉按钮,请点击您正在做的事! – Flood2d

+0

@ Flood2d我将它们添加到添加到添加到场景中的BorderPane的FlowPane中。是不是可以做?编辑:等等,我没有添加他们......我很密集。 – senpaimaster

+0

没关系,但是在您发布的代码中,我没有看到将它们添加到FlowPane的位置,您创建它们,将侦听器添加到btnExit,但不会将它们添加到FlowPane。如果你可以看到他们的图形,也许你省略了代码的一部分? – Flood2d

回答

2

更换

import edu.seminolestate.studentanalysis.ActionEvent; 
import edu.seminolestate.studentanalysis.EventHandler; 

import javafx.event.ActionEvent; 
import javafx.event.EventHandler; 

然后不要忘记将按钮添加到面板。