【发布时间】:2018-10-19 06:55:40
【问题描述】:
我是 JavaFx 的新手,实际上我正在尝试更改/设置标签文本。在我看来,我做了所有要做的事情,但它不起作用。希望有人可以帮助我。我现在正在寻找几个小时,但我想我永远找不到我的错误。此外,我想错误是在控制器上找到,但在我看过的一些示例中,它看起来类似于我的代码..
FXML:
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.SplitPane?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.text.Font?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<SplitPane id="Split" dividerPositions="0.3" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="620.0" prefWidth="871.0" xmlns="http://javafx.com/javafx/8.0.141" xmlns:fx="http://javafx.com/fxml/1" fx:controller="presentation.DataController">
<items>
<AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="160.0" prefWidth="100.0">
<children>
<Label id ="name" fx:id="name" layoutX="26.0" layoutY="21.0" prefHeight="576.0" prefWidth="205.0" textAlignment="CENTER"/>
</children></AnchorPane>
<AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="160.0" prefWidth="100.0">
<children>
<Label fx:id="daten" layoutX="19.0" layoutY="14.0" prefHeight="576.0" prefWidth="511.0"/>
<!-- <Slider layoutX="573.0" layoutY="11.0" orientation="VERTICAL" prefHeight="576.0" prefWidth="14.0" /> !-->
</children></AnchorPane>
</items>
</SplitPane>
我的控制器:
package presentation;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
public class DataController implements Initializable {
@FXML
private Label name;
private Label daten;
private void init() {
name.setText("Hello World!");
daten.setText("AnotherTest");
}
@Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
}
}
以及应用程序类
package presentation;
import application.*;
import data.*;
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.stage.Stage;
public class Data extends Application {
@Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("DataView.fxml"));
Scene scene = new Scene(root);
stage.setTitle("Übung 0");
stage.setScene(scene);
stage.show();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
【问题讨论】:
-
你的 init 方法永远不会被调用,是吗?
-
应该如何调用
init()?它被声明为private,并且不在其自己的类中调用。 -
是的,终于找到了……我太专注于另一个没有调用 init() 方法的示例……真是愚蠢的错误:s
-
init!=initialize所以它不会被FXMLLoader调用。此外,我不确定它不会使用Initializable.initialize代替。此外,此方法(以及第二个Label)对FXMLLoader不可见,因为它没有使用@FXML进行注释。在这种情况下,我看不出控制器这样做有什么好处。您可以简单地将属性text="some text"添加到 fxml 中的<Label>元素。
标签: java user-interface javafx label