我正在练习一个小的聊天框窗口,我尝试制作它,所以用户必须在文本框中输入一个名称(用户名),但我遇到了问题,我相信这不是第一次。每次我尝试使用其中一个变量时,我都会一直得到nullpointerexception,因为现在它是textfield。所以我初始化它,但即使我输入用户名,它总是空字符串。
app.java
public class app extends Application {
@Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("FXMLApp.fxml"));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch();
}
}
FXMLApp.fxml(删除了不需要的内容)
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.text.*?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<AnchorPane id="AnchorPane" maxHeight="900.0" maxWidth="800.0" minHeight="300.0" minWidth="200.0" prefHeight="600.0" prefWidth="500.0" xmlns="http://javafx.com/javafx/8.0.40" xmlns:fx="http://javafx.com/fxml/1" fx:controller="chatappclient.FXMLChatAppClientController">
<children>
<TextField fx:id="username" layoutX="176.0" layoutY="488.0" promptText="enter username" />
<Button fx:id="login" layoutX="176.0" layoutY="519.0" mnemonicParsing="false" onAction="#login" text="Login" />
</children>
</AnchorPane>
你可以看到登录按钮调用
onAction="#login"
最后一个文件:FXMLAppController
package chatappclient;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.layout.Pane;
import javax.swing.JOptionPane;
public class FXMLAppController implements Initializable
{
@FXML
private Pane top_container;
private Pane bottom_container;
private TextField username ;
private String name;
private Button login;
public FXMLChatAppClientController ()
{
// without this, I get nullpointerexception
// with it, the textfield is always null
username = new TextField();
}
@Override
public void initialize(URL url, ResourceBundle rb)
{}
@FXML
private void login()
{
// this returns empty string, if I did not initialize it, it would be an exception
System.out.println("DEBUG: " + username.getText());
}
}
答案 0 :(得分:1)
您需要使用@FXML
注释FXML文件中定义的每个字段:
private Pane top_container;
private Pane bottom_container;
@FXML
private TextField username ;
private String name;
@FXML
private Button login;