Java FX 8,设置文本字段的值时出错 [英] Java FX 8, trouble setting the value of text field

查看:104
本文介绍了Java FX 8,设置文本字段的值时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试填充Java FX中文本字段的值。

I'm trying to populate the value of a text field in Java FX.

我有主类,控制器和fxml.I已绑定带控制器的fxml文件及其中的相应字段。当我尝试设置其值时,它会失败。

I have the Main Class,the controller and the fxml.I have bind the fxml file with controller and the appropriate field in it. When i try to set its value, it fails.

Main.java

Main.java

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.FlowPane;
import javafx.stage.Stage;


public class Main extends Application {

    private Stage primaryStage;
    private FlowPane rootLayout;

    @Override
    public void start(Stage primaryStage) {
        try {


            FXMLLoader loader = new FXMLLoader();
            loader.setLocation(Main.class.getResource("test.fxml"));            
            rootLayout = (FlowPane) loader.load();                      
            Scene scene = new Scene(rootLayout);
            primaryStage.setScene(scene);
            primaryStage.show();



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

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

testController.java

testController.java

package application;

import javafx.fxml.FXML;
import javafx.scene.control.TextField;

public class testController {

    @FXML
    private TextField t1;

    public testController() {

        System.out.println("hi");
        t1 = new TextField("j");
        t1.setText("hi");

    }



}

FXML文件:

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

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

<FlowPane prefHeight="200.0" prefWidth="200.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.testController">
   <children>
      <TextField fx:id="t1" />
   </children>
</FlowPane>


推荐答案

你在错误的地方做这件事!如果您需要在加载fxml之前使用控件,则需要在 initialize() 。为此,您的控制器应实现 Initializable

You are doing it in the wrong place! If you need to play around with your controls just before your fxml is loaded, you need to do it in the initialize(). For this your controller should implement the Initializable

所以您的控制器变为:

public class testController implements Initializable{

    @FXML
    private TextField t1;

    public void initialize() {

        System.out.println("hi");

        //You should not re-initialize your textfield
        //t1 = new TextField("j");

        t1.setText("hi");

    }
}

这篇关于Java FX 8,设置文本字段的值时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆