簡體   English   中英

JavaFX-按鈕不起作用

[英]JavaFX - Button is not working

創建一個基於俄勒岡小徑的rpg游戲。 在控制器IntroControllerLeaderBoardController正常工作時,我無法使按鈕在handle作出反應。

IntroController包含從LeaderBoardController復制的兩個按鈕。

public class Main extends Application {

    public Stage stage;

    @Override
    public void start(Stage primaryStage) {
        try {
            this.stage = primaryStage;
            initLayout();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /*
     * initLayout contains the functionality to set up the root and scene of the
     * JavaFX view using the desired FXML file, without the mess in start.
     * 
     */
    public void initLayout() {
        try {
            System.out.println("Working Directory = " + System.getProperty("user.dir"));

            Parent root = FXMLLoader.load(getClass().getResource("/fxml/Intro.fxml"));

            Scene scene = new Scene(root);
            stage.setScene(scene);
            stage.show();
            stage.setMaxHeight(500);
            stage.setMaxWidth(750);
            stage.setResizable(false);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /*
     * switchScene added to clean up mounts of code in regards to switching a scene usually from an actionevent. Takes in a string 
     * .fxml location and the Stage.
     */
    public void switchScene(String fxml, Stage stage) {
        try {
            Parent root = FXMLLoader.load(getClass().getClassLoader().getResource(fxml));
            Scene scene = new Scene(root);
            stage.setScene(scene);
            stage.show();
            stage.setMaxHeight(500);
            stage.setMaxWidth(750);
            stage.setResizable(false);
        } catch (IOException e) {
            // TODO handle exception
            e.printStackTrace();
            System.out.println("ERROR: Unable to open " + fxml);
            stage.close();
        }

    }

    public static void main(String[] args) {
        launch(args);

    }
}
public class IntroController implements EventHandler<ActionEvent>, Initializable {


    @FXML
    Button mainMenuButton;

    @FXML
    Button exitButton;

    @FXML
    AnchorPane background;

    @FXML
    ImageView picture;

    Main main = new Main();


    @Override
    public void initialize(URL location, ResourceBundle resources) {
        showImage("images/cilantroRiceLogo.png");
    }

    /*
     * handle is used as the primary ActionEvent handler for actions such as
     * "when" something is clicked, "then" do so.
     * 
     * @param ActionEvent event
     */
    @Override
    public void handle(ActionEvent event) {
        Button selected = (Button) event.getSource();
        Stage stage = (Stage) selected.getScene().getWindow();

    if(selected == mainMenuButton) 
        main.switchScene("fxml/Title.fxml", stage);

    if(selected == exitButton) 
        stage.close();



        background.setOnKeyPressed(e -> {
            if (e.getCode() == KeyCode.ENTER) {
                main.switchScene("fxml/Title.fxml", stage);
            }

        });

    }

    private void showImage(String imageName) {
        Image image;

        try {
            image = new Image(new FileInputStream(imageName));

            if (imageName.equals("images/cilantroRiceLogo.png"))
                picture.setImage(image);

        } catch (FileNotFoundException e) {
            // TODO handle exception!!
            e.printStackTrace();
        }
    }
}
public class LeaderboardController implements EventHandler<ActionEvent>, Initializable {

    @FXML
    Button exitButton, mainMenuButton;

    @FXML
    TableView leaderTable;

    @FXML
    TableColumn rankColumn, nameColumn, difficultyColumn, scoreColumn;

    Main main = new Main();

    private ObservableList<Score> scores = FXCollections.observableArrayList();
    private Leaderboard leaderboard;

    @Override
    public void initialize(URL arg0, ResourceBundle arg1) { 

        leaderboard = new Leaderboard();
        setScores();

        rankColumn.setCellValueFactory(new PropertyValueFactory<Score, String>("rank"));
        nameColumn.setCellValueFactory(new PropertyValueFactory<Score, String>("userName"));
        difficultyColumn.setCellValueFactory(new PropertyValueFactory<Score, String>("difficulty"));
        scoreColumn.setCellValueFactory(new PropertyValueFactory<Score, String>("finalScore"));

        leaderTable.setItems(scores);
    }

    @Override
    public void handle(ActionEvent event) {
        Button selected = (Button) event.getSource();
        Stage stage = (Stage) selected.getScene().getWindow();

        if(selected == mainMenuButton) 
            main.switchScene("fxml/Title.fxml", stage);

        if(selected == exitButton) 
            stage.close();

    }

    /**
     * populates scores with the Scores from leaderboard.scores
     */
    public void setScores() {
        for(Score score : leaderboard.getScores()) {
            scores.add(score);
        }
    }
}

Intro.fxml

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

<?import javafx.scene.*?>
<?import javafx.scene.shape.*?>
<?import javafx.scene.text.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.image.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.layout.AnchorPane?>

<AnchorPane xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.controller.IntroController">
   <children>
      <AnchorPane fx:id="background" disable="true" onKeyTyped="#handle" prefHeight="500.0" prefWidth="750.0" style="-fx-background-color: #303030;">
         <children>
            <ImageView fx:id="picture" fitHeight="327.0" fitWidth="446.0" layoutX="176.0" layoutY="25.0" onMouseClicked="#handle" pickOnBounds="true" preserveRatio="true">
            </ImageView>
            <Button fx:id="exitButton" layoutX="444.0" layoutY="387.0" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" mnemonicParsing="false" onAction="#handle" prefHeight="60.0" prefWidth="239.0" style="-fx-background-color: #7f7f7f;" text="Exit Game">
               <cursor>
                  <Cursor fx:constant="HAND" />
               </cursor>
               <font>
                  <Font name="Magneto Bold" size="29.0" />
               </font>
            </Button>
            <Button fx:id="mainMenuButton" alignment="CENTER" layoutX="53.0" layoutY="387.0" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" mnemonicParsing="false" onAction="#handle" prefHeight="60.0" prefWidth="239.0" style="-fx-background-color: #7f7f7f;" text="Main Menu" textAlignment="CENTER" wrapText="true">
               <cursor>
                  <Cursor fx:constant="HAND" />
               </cursor>
               <font>
                  <Font name="Magneto Bold" size="29.0" />
               </font>
            </Button>
         </children>
      </AnchorPane>
   </children>
</AnchorPane>

Leaderboard.fxml

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

<?import javafx.scene.*?>
<?import javafx.scene.paint.*?>
<?import javafx.scene.effect.*?>
<?import javafx.scene.text.*?>
<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.layout.BorderPane?>

<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="500.0" prefWidth="750.0" style="-fx-background-color: #000000;" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.controller.LeaderboardController">
   <children>
      <TableView fx:id="leaderTable" layoutX="122.0" layoutY="110.0" prefHeight="287.0" prefWidth="510.0" style="-fx-background-color: #666666; -fx-overflow-x: none;" AnchorPane.bottomAnchor="103.0" AnchorPane.topAnchor="110.0">
        <columns>
            <TableColumn fx:id="rankColumn" minWidth="20.0" prefWidth="49.0" text="Rank" />
          <TableColumn fx:id="nameColumn" editable="false" minWidth="173.0" prefWidth="232.0" resizable="false" sortable="false" text="Name" />
            <TableColumn fx:id="difficultyColumn" editable="false" minWidth="30.0" prefWidth="89.0" resizable="false" sortable="false" text="Difficulty" />
          <TableColumn fx:id="scoreColumn" editable="false" minWidth="90.0" prefWidth="138.0" resizable="false" sortType="DESCENDING" sortable="false" text="Score" />
        </columns>
         <columnResizePolicy>
            <TableView fx:constant="CONSTRAINED_RESIZE_POLICY" />
         </columnResizePolicy>
      </TableView>
      <Button fx:id="mainMenuButton" alignment="CENTER" layoutX="85.0" layoutY="419.0" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" mnemonicParsing="false" onAction="#handle" prefHeight="60.0" prefWidth="239.0" style="-fx-background-color: #7f7f7f;" text="Main Menu" textAlignment="CENTER" wrapText="true" AnchorPane.bottomAnchor="21.0" AnchorPane.leftAnchor="85.0" AnchorPane.rightAnchor="426.0">
         <font>
            <Font name="Magneto Bold" size="29.0" />
         </font>
         <cursor>
            <Cursor fx:constant="HAND" />
         </cursor></Button>
      <Button fx:id="exitButton" layoutX="421.0" layoutY="419.0" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" mnemonicParsing="false" onAction="#handle" prefHeight="60.0" prefWidth="239.0" style="-fx-background-color: #7f7f7f;" text="Exit Game" AnchorPane.bottomAnchor="21.0" AnchorPane.leftAnchor="426.0" AnchorPane.rightAnchor="85.0">
         <font>
            <Font name="Magneto Bold" size="29.0" />
         </font>
         <cursor>
            <Cursor fx:constant="HAND" />
         </cursor></Button>
      <Label alignment="CENTER" layoutX="169.0" layoutY="14.0" prefHeight="88.0" prefWidth="410.0" text="Leaderboard" textAlignment="CENTER" textFill="#f5f5f5" wrapText="true" AnchorPane.leftAnchor="169.0" AnchorPane.rightAnchor="171.0">
         <font>
            <Font name="Old English Text MT" size="72.0" />
         </font>
         <effect>
            <DropShadow blurType="ONE_PASS_BOX" offsetX="2.0" offsetY="2.0" />
         </effect>
      </Label>
   </children>
</AnchorPane>

加載項目很難分辨。 通常我要做的是在init方法中設置Handler,看看是否可以觸發它。

另一個隨機的嘗試是讓處理程序使用基本Event: https : //docs.oracle.com/javase/8/javafx/api/javafx/event/Event.html

因此,此問題已解決,是由Github合並/拉出錯誤引起的。 兩者之間的某個原因導致了錯誤,並破壞了這兩個特定文件,並且通過更正該錯誤,它已得到解決。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM