java - JavaFX 8 FXML TextField (maybe other variables) are always null -
i practicing small chat box window , try make user must enter name textfield box (a username) been having problems , sure not first time. keep getting nullpointerexception every time try use 1 of variables, right now, textfield. initialize blank string when type in username.
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 (deleted not needed)
<?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>
as can see login button calls
onaction="#login"
last file: 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, nullpointerexception // it, textfield null username = new textfield(); } @override public void initialize(url url, resourcebundle rb) {} @fxml private void login() { // returns empty string, if did not initialize it, exception system.out.println("debug: " + username.gettext()); } }
you need annotate each of fields defined in fxml file @fxml
:
private pane top_container; private pane bottom_container; @fxml private textfield username ; private string name; @fxml private button login;
Comments
Post a Comment