通过按下同一场景上的按钮来更改Label的“文本”Works,但如果按钮不在同一场景上,则它不起作用。为什么?

问题描述 投票:0回答:1

背景资料:

Java FXML为您实例化变量。它不需要再次明确地完成,否则将丢失FXML创建的引用。

仅在方法上需要注释@FXML以确保注入它。尽管将它置于变量之上是一种好习惯,但它并没有解决问题

我正在尝试更改标签的文本,因为我最终想要显示特定的错误消息供用户阅读。目前我给标签留下了文字“标签”。当我运行程序时,我注意到如果我加载一个新场景,然后单击按钮来更改它工作的标签,但如果我尝试加载场景“下一步”并尝试更改标签的文本我得到一个空指针错误。因此Main.next()之后的行将给我空指针,但如果我把它取出然后单击“确定”按钮然后更改它工作的标签的文本。问题是我希望它通过更改标签显示不同的错误消息,我想在加载场景后立即显示它。谁可以帮我这个事?

`<VBox alignment="CENTER" maxHeight="-Infinity" maxWidth="-Infinity" 
minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" 
prefWidth="600.0" 
xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" 
fx:controller="sample.Controller">
<children>
<Label fx:id="lb2" alignment="CENTER" text="Label" />
<Button fx:id="ok" mnemonicParsing="false" onAction="#ok" text="Button" />
</children>
</VBox>`




<Pane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" 
minWidth="-Infinity" prefHeight="300.0" prefWidth="600.0" 
xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" 
fx:controller="sample.Controller">
<children>
  <Button fx:id="pushMe" layoutX="79.0" layoutY="80.0" 
mnemonicParsing="false" onAction="#pushMeAction" text="Push me" />
</children>
</Pane>



 package sample;

 import javafx.fxml.FXML;
 import javafx.scene.control.Button;
 import javafx.scene.control.Label;
 import javafx.scene.text.Text;
 import javafx.scene.text.TextFlow;
 import java.awt.*;
 import java.io.IOException;
 import java.util.Timer;
 import java.util.concurrent.TimeUnit;

 public class Controller
 {
    @FXML
    public Button pushMe;
    public Label lb2;


    public void pushMeAction() throws Exception
    {
        Text text1 = new Text("Hello World");

        Main.next();
        lb2.setText("Hello");

    }

    public void ok()
    {
        lb2.setText("Hello");
    }
 }



 public class Main extends Application {

    public static Stage primaryStage;

    @Override
    public void start(Stage primaryStage) throws Exception{
        Parent root =FXMLLoader.load(getClass().getResource("sample.fxml"));
        this.primaryStage=primaryStage;
        this.primaryStage.setTitle("Hello World");
        this.primaryStage.setScene(new Scene(root, 300, 275));
        this.primaryStage.show();
    }

    public static void next() throws IOException
    {
        Pane menu = FXMLLoader.load(Main.class.getResource("next.fxml"));
        Scene myScene = new Scene(menu);
        primaryStage.setScene(myScene);

    }


    public static void main(String[] args) {
        launch(args);
    }
}
java label
1个回答
0
投票

你应该这样写:

@FXML
public Button pushMe;

@FXML
public Label lb2;

@FXML
public Button ok;

@FMXL
public void pushMeAction(ActionEvent event) throws Exception
{
Text text1 = new Text("Hello World");

Main.next();
lb2.setText("Hello");

}

@FXML
public void ok(ActionEvent event)
{
    lb2.setText("Hello");
}
© www.soinside.com 2019 - 2024. All rights reserved.