如何使用eclipse和场景构建器更改java中的标签文本?

时间:2014-12-16 07:17:58

标签: java eclipse javafx scenebuilder

我试图制作一个" Hello World"使用eclipse和场景构建器。

package lj.HelloWorld;
import java.io.IOException;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.BorderPane;

public class HelloWorld extends Application {
    private Stage primaryStage;
    private BorderPane rootLayout;

@Override
public void start(Stage primaryStage) {
    this.primaryStage = primaryStage;
    this.primaryStage.setTitle("AddressApp");

    initRootLayout();
}

/**
 * Initializes the root layout.
 */
public void initRootLayout() {
    try {
        // Load root layout from fxml file.
        FXMLLoader loader = new FXMLLoader();
        loader.setLocation(HelloWorld.class.getResource("rootHelloWorld.fxml"));
        rootLayout = (BorderPane) loader.load();

        // Show the scene containing the root layout.
        Scene scene = new Scene(rootLayout);
        primaryStage.setScene(scene);
        primaryStage.show();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
// my attempt to refer to my label object in scenebuilder.
@FXML
private Label lblOutput;

@FXML
private void handleClick(ActionEvent event) {
    lblOutput.setText("This");
}
}

这是我的fxml

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

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

<BorderPane prefHeight="200.0" prefWidth="300.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1">
   <center>
      <Pane prefHeight="200.0" prefWidth="200.0" BorderPane.alignment="CENTER">
         <children>
            <Button fx:id="btnClick" layoutX="98.0" layoutY="14.0" mnemonicParsing="false" text="Click Me" />
            <Label fx:id="lblOutput" layoutX="167.0" layoutY="18.0" text="1231231" />
         </children>
      </Pane>
   </center>
</BorderPane>

我只想知道如何引用标签并将其文本更改为&#34; Hello World&#34;。 PS:我是从vb.net学习java的。我曾尝试在谷歌上寻找一个Hello World样本,但有些网站已关闭,其他网站对我来说太复杂了。就像ch.makery教程一样。

2 个答案:

答案 0 :(得分:2)

您需要一个Controller类

package lj.HelloWorld;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.text.Text;
 public class FXMLDocumentController {

@FXML private Label lblOutput;

@FXML protected void handleButtonAction(ActionEvent e){
lblOutput.setText("Hello World");
}
}

告诉你的XML控制器类

 <BorderPane  fx:controller="lj.HelloWorld.FXMLDocumentController"
  <Button fx:id="btnClick" layoutX="98.0" layoutY="14.0" mnemonicParsing="false"    text="Click Me"
onAction="#handleButtonAction"/>

有关详细信息和教程请阅读:http://docs.oracle.com/javafx/2/get_started/hello_world.htm

答案 1 :(得分:0)

您可以尝试从标签实例中引用,例如: lbl.setText("Hello World");