【问题标题】:JavaFX Label not updating with setText()JavaFX 标签未使用 setText() 更新
【发布时间】:2017-05-05 17:13:16
【问题描述】:

我进行了大量搜索,但似乎找不到解决问题的方法,我正在尝试在用户在 Intro.fxml 中输入他/她的姓名时更新标签 selectedName并出现在 Main.fxml 上。但是它仍然显示为在初始化方法中设置的 default_user。诚然,代码有点乱,但这只是我正在做的一个小项目。

LogicController.java 不是整个文件

public class LogicController{ 

/** CLASS OBJECTS
 * 
 */

private LoadWords loadWords = new LoadWords();
private GameLogic game = new GameLogic();

/** AUDIO FILES 
 * items used for audio
 * All wavs are free
 * provided on freesound.org
 * **/

final URL resource = getClass().getResource("sounds/beep.wav");
final AudioClip menuClick = new AudioClip(resource.toString());

/** OTHER DECLARATIONS
 * other variables
 * 
 * 
 */

@FXML public ChoiceBox<String> difficultyBox = new ChoiceBox<String>();
@FXML public ObservableList<String> difficultyBoxList = FXCollections.observableArrayList("Easiest", "Easy", "Medium", "Hard");
@FXML public String selectedDifficulty; 
@FXML public TextField myName;
@FXML public Label selectedName = new Label(); 

@FXML  
public void initialize()
{
  difficultyBox.setItems(difficultyBoxList);
  selectedName.setText("default_player");


}


@FXML
public void loadSerial(MouseEvent mouseEvent) { 

    menuClick.play();
    loadWords.startSequential();    

    game.setAllLists(loadWords.getAllLists());
    game.setDifficulty(difficultyBox.getSelectionModel().getSelectedItem().toString());
    game.setName(myName.getText());
    selectedName.setText(game.getName().toString());

    try{

        Node  source = (Node)  mouseEvent.getSource(); 
        Stage intro  = (Stage) source.getScene().getWindow();
        intro.close();          

        Parent root = FXMLLoader.load(getClass().getResource("Main.fxml")); 
        root.setId("pane");

        Scene scene = new Scene(root, 900, 506);
        Stage primaryStage = new Stage();

        primaryStage.setTitle("x");
        scene.getStylesheets().addAll(this.getClass().getResource("application.css").toExternalForm());
        primaryStage.setResizable(false);
        primaryStage.setScene(scene);
        primaryStage.show();

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


}

Intro.fxml

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

<?import javafx.scene.control.ChoiceBox?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.effect.DropShadow?>
<?import javafx.scene.effect.Glow?>
<?import javafx.scene.image.Image?>
<?import javafx.scene.image.ImageView?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.ColumnConstraints?>
<?import javafx.scene.layout.FlowPane?>
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.layout.Pane?>
<?import javafx.scene.layout.RowConstraints?>
<?import javafx.scene.layout.StackPane?>
<?import javafx.scene.text.Font?>

<AnchorPane id="fx" prefHeight="538.0" prefWidth="923.0" style="-fx-background-color: #4f0f41;" xmlns="http://javafx.com/javafx/8.0.60" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.LogicController">
   <children>
      <StackPane prefHeight="538.0" prefWidth="923.0">
         <children>
            <Pane prefHeight="545.0" prefWidth="929.0">
               <children>
                  <Label layoutX="265.0" layoutY="101.0" prefHeight="103.0" prefWidth="394.0" style="-fx-font-family: Paperland; -fx-font-size: 90;" stylesheets="@application.css" text="FANGMAN" textFill="WHITE">
                     <effect>
                        <Glow />
                     </effect>
                     <font>
                        <Font size="66.0" />
                     </font>
                  </Label>
                  <Label layoutX="265.0" layoutY="69.0" prefHeight="65.0" prefWidth="79.0" style="-fx-font-family: Paperland; -fx-font-size: 40;" stylesheets="@application.css" text="THE" textFill="WHITE">
                     <effect>
                        <Glow />
                     </effect>
                  </Label>
                  <Label layoutX="694.0" layoutY="24.0" text="An adaptation by Benjamin Meysner" textFill="WHITE" />
                  <FlowPane layoutX="266.0" layoutY="288.0" prefHeight="225.0" prefWidth="378.0">
                     <children>
                        <GridPane prefHeight="230.0" prefWidth="398.0">
                          <columnConstraints>
                            <ColumnConstraints hgrow="SOMETIMES" maxWidth="171.0" minWidth="10.0" prefWidth="171.0" />
                            <ColumnConstraints hgrow="SOMETIMES" maxWidth="265.0" minWidth="10.0" prefWidth="64.0" />
                              <ColumnConstraints hgrow="SOMETIMES" maxWidth="233.0" minWidth="0.0" prefWidth="152.0" />
                          </columnConstraints>
                          <rowConstraints>
                            <RowConstraints />
                            <RowConstraints maxHeight="51.0" minHeight="5.0" prefHeight="48.0" />
                            <RowConstraints maxHeight="172.0" minHeight="10.0" prefHeight="109.0" vgrow="SOMETIMES" />
                              <RowConstraints maxHeight="78.0" minHeight="10.0" prefHeight="41.0" vgrow="SOMETIMES" />
                              <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
                          </rowConstraints>
                           <children>
                              <ImageView id="zomb" fx:id="zomb" fitHeight="150.0" fitWidth="200.0" onMouseClicked="#loadSerial" onMouseEntered="#zombieHover" pickOnBounds="true" preserveRatio="true" style="-fx-cursor: hand;" styleClass="zomb" GridPane.rowIndex="2">
                                 <image>
                                    <Image url="@images/chtr1.png" />
                                 </image>
                                 <effect>
                                    <Glow />
                                 </effect>
                              </ImageView>
                              <ImageView id="skul" fitHeight="150.0" fitWidth="200.0" onMouseClicked="#loadParallel" onMouseEntered="#skulHover" pickOnBounds="true" preserveRatio="true" style="-fx-cursor: hand;" styleClass="skul" GridPane.columnIndex="2" GridPane.rowIndex="2">
                                 <image>
                                    <Image url="@images/chtr3.png" />
                                 </image>
                                 <effect>
                                    <Glow />
                                 </effect>
                              </ImageView>
                              <Label alignment="CENTER" style="-fx-font-family: Paperland;" text="OR" textFill="WHITE" GridPane.columnIndex="1" GridPane.rowIndex="2">
                                 <font>
                                    <Font size="50.0" />
                                 </font>
                                 <effect>
                                    <Glow />
                                 </effect>
                              </Label>
                              <Label text="Serial" textFill="WHITE" GridPane.rowIndex="3" />
                              <Label text="Parallel" textFill="WHITE" GridPane.columnIndex="2" GridPane.rowIndex="3" />
                           </children>
                        </GridPane>
                     </children>
                  </FlowPane>
                  <ImageView fitHeight="104.0" fitWidth="113.0" layoutX="156.0" layoutY="90.0" pickOnBounds="true" preserveRatio="true">
                     <image>
                        <Image url="@images/drac.png" />
                     </image>
                  </ImageView>
                  <Label layoutX="252.0" layoutY="262.0" prefHeight="52.0" prefWidth="137.0" text="Now enter your name..." textFill="WHITE" />
                  <Label layoutX="252.0" layoutY="203.0" prefHeight="78.0" prefWidth="137.0" text="To begin a new game, select a difficulty setting..." textFill="WHITE" wrapText="true" />
                  <TextField fx:id="myName" layoutX="405.0" layoutY="276.0" promptText="Enter name...">
                     <effect>
                        <DropShadow height="71.4" radius="30.7525" spread="0.13" width="53.61" />
                     </effect></TextField>
                  <Label layoutX="115.0" layoutY="281.0" prefHeight="78.0" prefWidth="137.0" text="Finally select a load option (Serial or Parallel)" textFill="WHITE" wrapText="true" />
                  <ChoiceBox fx:id="difficultyBox" layoutX="404.0" layoutY="225.0" prefWidth="150.0" value="Easiest">
                     <effect>
                        <DropShadow height="0.0" radius="29.2125" spread="0.19" width="118.85" />
                     </effect>
                  </ChoiceBox>
               </children>
            </Pane>
         </children>
      </StackPane>
   </children>
</AnchorPane>

Main.fxml

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

<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.effect.Glow?>
<?import javafx.scene.image.Image?>
<?import javafx.scene.image.ImageView?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.ColumnConstraints?>
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.layout.Pane?>
<?import javafx.scene.layout.RowConstraints?>
<?import javafx.scene.text.Font?>

<AnchorPane style="-fx-background-color: #4f0f41;" stylesheets="@application.css" xmlns="http://javafx.com/javafx/8.0.60" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.LogicController">
   <children>
      <Pane prefHeight="506.0" prefWidth="900.0" stylesheets="@application.css">
         <children>
            <ImageView fitHeight="197.0" fitWidth="183.0" layoutX="35.0" pickOnBounds="true" preserveRatio="true">
               <image>
                  <Image url="@images/drac.png" />
               </image>
            </ImageView>
            <Label layoutX="37.0" layoutY="223.0" text="Welcome" textFill="WHITE" />
            <Label fx:id="selectedName" layoutX="97.0" layoutY="218.0" prefHeight="27.0" prefWidth="121.0" text="  " textFill="WHITE">
               <font>
                  <Font size="13.0" />
               </font>
               <effect>
                  <Glow />
               </effect>
            </Label>
            <Pane layoutX="24.0" layoutY="211.0" opacity="0.45" prefHeight="127.0" prefWidth="200.0" style="-fx-background-color: BLACK;">
               <children>
                  <GridPane layoutX="13.0" layoutY="34.0" prefHeight="81.0" prefWidth="153.0">
                    <columnConstraints>
                      <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
                      <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
                    </columnConstraints>
                    <rowConstraints>
                      <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
                      <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
                        <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
                    </rowConstraints>
                     <children>
                        <Label text="Games Won" textFill="WHITE" />
                        <Label text="Games Lost" textFill="WHITE" GridPane.rowIndex="1" />
                        <Label text="Win Ratio" textFill="WHITE" GridPane.rowIndex="2" />
                        <Label text="0" textFill="WHITE" GridPane.columnIndex="1" />
                        <Label text="0" textFill="WHITE" GridPane.columnIndex="1" GridPane.rowIndex="1" />
                        <Label text="0%" textFill="WHITE" GridPane.columnIndex="1" GridPane.rowIndex="2" />
                     </children>
                  </GridPane>
               </children>
            </Pane>
            <Pane layoutX="246.0" layoutY="61.0" opacity="0.45" prefHeight="421.0" prefWidth="633.0" style="-fx-background-color: BLACK;" />
            <Button layoutX="355.0" layoutY="22.0" mnemonicParsing="false" prefHeight="26.0" prefWidth="100.0" text="save game" />
            <Pane layoutX="25.0" layoutY="373.0" opacity="0.45" prefHeight="104.0" prefWidth="200.0" style="-fx-background-color: BLACK;" />
            <Button layoutX="244.0" layoutY="22.0" mnemonicParsing="false" prefHeight="26.0" prefWidth="100.0" text="load game" />
            <Button layoutX="469.0" layoutY="22.0" mnemonicParsing="false" onAction="#newWord" prefHeight="26.0" prefWidth="100.0" text="new word" />
            <Label layoutX="28.0" layoutY="484.0" text="message box" textFill="WHITE" />
            <Label layoutX="28.0" layoutY="346.0" text="statistics" textFill="WHITE" />
            <Label layoutX="246.0" layoutY="484.0" text="game view" textFill="WHITE" />
         </children>
      </Pane>
   </children>
</AnchorPane>

图片在这里 intro.fxml main.fxml 任何帮助将不胜感激!

【问题讨论】:

  • 您的两个 FXML 文件具有相同的控制器。你不需要在他们两个中使用fx:controller。这是that上的一个问题
  • @Shashwat 实际上,它们“没有相同的控制器”。每次加载这些 FXML 文件中的任何一个时,都会创建一个新控制器:但是两个 FXML 文件的控制器来自同一个类。 (“成为同一个对象”和“两个对象来自同一个类”之间有很大的区别。)这样做通常是一个非常糟糕的主意:应该有一个不同的控制器 class对于每个 FXML 文件。

标签: java javafx controller fxml scenebuilder


【解决方案1】:

你的变量已经注解@FXML所以不需要实例化它:

//Wrong
@FXML public Label selectedName = new Label ();

//Correct
@FXML public Label selectedName;

编辑:

其他带注释的项目也一样,并尝试实现 Initializable :

LogicController implements Initializable{

【讨论】:

  • 如果我把它取出来,我得到一个空指针异常code 原因:java.lang.NullPointerException at application.LogicController.initialize(LogicController.java:56) ... 27 更多跨度>
  • 尝试发布完整代码或仅发布LogicController 的第 56 行
  • 依然得到同一行抛出空指针异常,selectedName.setText("default_player");
  • 第 56 行:selectedName.setText("default_player");
  • 感谢您的帮助
【解决方案2】:

Intro.fxml 使用的控制器实例与Main.fxml 使用的控制器实例不同。您需要在加载 fxml 之前指定控制器实例以使用相同的实例:

FXMLLoader loader = new FXMLLoader(getClass().getResource("Main.fxml"));
loader.setController(this);
Parent root = loader.load();

// fill data to the field just created when loading the fxml
selectedName.setText(game.getName().toString());

(这需要从Main.fxml 中删除fx:controller 属性。)

请注意,这种方式初始化被调用了两次。恕我直言,使用单独的控制器会更好。

有多种方法可以将信息传递给 fxml 文件的控制器,这些方法可能比上述方法更适合,例如访问FXMLLoader创建的控制器实例。

请注意,初始化应该从 fxml 注入以防止 NPE 的字段很少是一个好主意,因为这只是错误的症状,并且您初始化字段的值与从fxml。

【讨论】:

  • 我从 Label selectedName 中删除了实例化位,并在 loadSerial 方法中添加了以下内容。 codetry{ 节点源 = (Node) mouseEvent.getSource();舞台介绍 = (Stage) source.getScene().getWindow();介绍.close(); FXMLLoader loader = new FXMLLoader(getClass().getResource("Main.fxml")); loader.setController(this);父根 = loader.load(); code .. 仍然得到标签的空指针
  • 还从 main.fxml 中删除了 fx:controller 属性
  • @benjay_uk FWIW 我什至不会尝试对两个不同的 FXML 文件使用相同的控制器或同一类的控制器。为每个 FXML 文件定义不同的控制器类,并在需要时在它们之间进行数据通信。
  • @benjay_uk 如果您使用相同的控制器实例,则每次对注入字段的访问都需要在调用load() 之后进行。在这种情况下,您正在从 initialize 方法访问该字段,该方法无法初始化未由 fxml 注入的内容。顺便说一句:无论如何你都在 fxml 中分配了内容,那么为什么用常量覆盖 initialize 方法中的值呢?
猜你喜欢
  • 2018-10-19
  • 1970-01-01
  • 2018-04-19
  • 2020-06-22
  • 1970-01-01
  • 1970-01-01
  • 2015-07-08
  • 1970-01-01
  • 2016-05-10
相关资源
最近更新 更多