【问题标题】:JavaFX - Button is not workingJavaFX - 按钮不起作用
【发布时间】:2019-01-17 04:43:25
【问题描述】:

创建一个基于俄勒冈小道的小型 rpg 游戏。在控制器IntroController 上,我无法在handle 内做出按钮反应,而LeaderBoardController 工作正常。

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>

排行榜.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>

【问题讨论】:

  • 您不需要使用控制器类实现EventHandler。事实上,我建议在您确切知道自己在做什么之前不要这样做。无论方法名称如何,fxml 中的#methodName 属性值都可以工作,并且不需要实现接口。您只需要确保方法签名是适当的。这允许您使用不同的方法来处理应该执行不同代码的不同节点上的事件。同样这样你可以处理不同的事件类型,你的代码没有onKeyTyped->KeyEvent, onMouseClicked->MouseEvent
  • 首先感谢@fabian 编辑问题的格式,我真的很感激。我已经删除了 onKeyTyped KeyEvent,但至于按钮我是否尝试使用 if '((Button) event.getSource() == mainMenu)' 或 if '(mainMenu.onMouseClicked != null)' [同时指定 #handle 在 SceneBuilder 的分配位置],这些解决方案都不适合我。

标签: java button javafx


【解决方案1】:

所以,这是由 Github 合并/拉取错误引起的。导致错误并破坏了这两个特定文件并通过更正该错误已解决的问题。

【讨论】:

    【解决方案2】:

    如果不加载项目,这很难说。通常我会在 init 方法中设置 Handler 并查看是否可以触发它。

    要尝试的另一件事是让您的处理程序使用基本事件:https://docs.oracle.com/javase/8/javafx/api/javafx/event/Event.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-08-27
      • 2020-03-14
      • 1970-01-01
      • 2011-12-02
      相关资源
      最近更新 更多