Textfield Arabic output shows strange characters javaFX - java

I'm working on a desktop application using javaFX, I'm using scene builder version 11 to create my interface that contains TextFields and ChoiceBox, my inputs are supposed to be set in Arabic. The problem is when I retrieve the text from the TextFiled or the ChoiceBox and print it in the console it shows characters like that "بننلنلن" and it also generates a problem to store the inputs in database, this is the SQLException:
java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'بننلنلن,نبلنبنلب,2021-06-30,أمر جزائي,تم التبليغ
When I tried another project without scene builder I got the Arabic outputs correctly, could scene bulider be the problem's origin?
here is my fxml file:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.geometry.Insets?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.ChoiceBox?>
<?import javafx.scene.control.DatePicker?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.HBox?>
<?import javafx.scene.layout.VBox?>
<AnchorPane id="AnchorIns" prefHeight="529.0" prefWidth="523.0" stylesheets="#newinsc.css" xmlns="http://javafx.com/javafx/11.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="newInsc.NewInscController">
<children>
<VBox fx:id="boxContainer" layoutX="139.0" layoutY="99.0" prefHeight="273.0" prefWidth="245.0">
<children>
<HBox alignment="CENTER_RIGHT" prefHeight="42.0" prefWidth="245.0">
<children>
<TextField fx:id="firstNameTxtField" alignment="CENTER_RIGHT" />
<Label alignment="CENTER_RIGHT" contentDisplay="RIGHT" prefHeight="17.0" prefWidth="71.0" stylesheets="#newinsc.css" text="الاسم" />
</children>
</HBox>
<HBox alignment="CENTER_RIGHT" prefHeight="42.0" prefWidth="245.0">
<children>
<TextField fx:id="lastNameTxtField" alignment="CENTER_RIGHT" />
<Label prefHeight="17.0" prefWidth="71.0" text="اللقب" />
</children>
</HBox>
<HBox alignment="CENTER_RIGHT" prefHeight="42.0" prefWidth="245.0">
<children>
<ChoiceBox fx:id="docTypeChoice" prefWidth="150.0" />
<Label prefHeight="17.0" prefWidth="71.0" text="نوع التبليغ" />
</children>
</HBox>
<HBox alignment="CENTER_RIGHT" prefHeight="42.0" prefWidth="245.0">
<children>
<DatePicker fx:id="dateField" prefHeight="25.0" prefWidth="149.0" />
<Label prefHeight="17.0" prefWidth="71.0" text="التاريخ" />
</children>
</HBox>
<HBox alignment="CENTER_RIGHT" prefHeight="42.0" prefWidth="245.0">
<children>
<ChoiceBox fx:id="tablighCase" prefWidth="150.0" />
<Label prefHeight="17.0" prefWidth="71.0" text="حالة التبليغ" />
</children>
</HBox>
<HBox alignment="CENTER" onMouseClicked="#cancelBtnClicked" prefHeight="46.0" prefWidth="245.0">
<children>
<Button fx:id="cancleBtn" mnemonicParsing="false" onMouseClicked="#cancelBtnClicked" text="الغاء">
<HBox.margin>
<Insets right="16.0" />
</HBox.margin>
</Button>
<Button fx:id="saveInscBtn" mnemonicParsing="false" onMouseClicked="#registerBtnClicked" text="تسجيل" />
</children>
</HBox>
</children>
</VBox>
</children>
</AnchorPane>
and this here is my controller file:
package newInsc;
import DB.dbConnection;
import java.net.URL;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.LocalDate;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.DatePicker;
import javafx.scene.control.TextField;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
/**
* FXML Controller class
*
* #author asus
*/
public class NewInscController implements Initializable {
#FXML
private ChoiceBox<String> docTypeChoice;
#FXML
private ChoiceBox<String> tablighCase;
#FXML
private DatePicker dateField;
#FXML
private Button saveInscBtn;
#FXML
private TextField firstNameTxtField;
#FXML
private TextField lastNameTxtField;
#FXML
private Button cancleBtn;
private Connection c;
private Statement s;
#FXML
private VBox boxContainer;
#Override
public void initialize(URL url, ResourceBundle rb) {
docTypeChoice.getItems().add("أمر جزائي");
docTypeChoice.getItems().add("حكم جزائي" );
docTypeChoice.getItems().add("تكليف بالحضور" );
docTypeChoice.getItems().add("قرار جزائي" );
tablighCase.getItems().add("تم التبليغ");
tablighCase.getItems().add("ترك اشعار");
tablighCase.getItems().add("عدم التمكن من التبليغ");
}
#FXML
private void cancelBtnClicked(MouseEvent event) {
Stage s = (Stage) cancleBtn.getScene().getWindow();
}
#FXML
private void registerBtnClicked(MouseEvent event) {
try {
String query;
String fname = firstNameTxtField.getText();
String lname = lastNameTxtField.getText();
LocalDate date = dateField.getValue();
String docType = docTypeChoice.getValue();
String state = tablighCase.getValue();
query = "insert into infotable values " + fname + "," + lname + "," + date+ ","+ docType+"," +state ;
dbConnection dbc = new dbConnection();
s = dbc.createConnection().createStatement();
s.execute(query);
s.close();
} catch (SQLException ex) {
Logger.getLogger(NewInscController.class.getName()).log(Level.SEVERE, null, ex);
}
}
}

I could find a solution, before I run the program I first compile it with F9 key then I run it with a key combination SHIFT + F6

Related

Cannot resolve method 'setCellValueFactory' in 'TableColumn'

I have no idea why I get this error message:
Cannot resolve method 'setCellValueFactory' in 'TableColumn'
But when I change to this code in initialize with a test variable, the error message get away:
#Override
public void initialize(URL url, ResourceBundle resourceBundle) {
javafx.scene.control.TableColumn kol2 = null;
kol2.setCellValueFactory(new PropertyValueFactory<Tabellmodell,String>("name"));
}
Does anyone know what the problem is with my original code?
package com.example.oppgave;
import javax.swing.table.TableColumn;
import com.example.oppgave.Modell.Ansatt;
import com.example.oppgave.Modell.Tabellmodell;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import java.net.URL;
import java.sql.*;
import java.util.ResourceBundle;
public class AnsattController implements Initializable {
#FXML
private Label tilbakemelding;
#FXML
private TextField innputNavn;
#FXML
private TextField innputId;
#FXML
private TableView<Tabellmodell> ansattTabell;
#FXML
private TableColumn kolname;
#FXML
private TableColumn kolid;
ObservableList<Tabellmodell> oblist= FXCollections.observableArrayList();
#Override
public void initialize(URL url, ResourceBundle resourceBundle) {
kolname.setCellValueFactory(new PropertyValueFactory<Tabellmodell,String>("name"));
}
private void listAnsatteTabell(){
int c;
try{
Db nyDb= new Db();
Connection tilkobling=nyDb.dbnyTilkobling();
Statement stmt=tilkobling.createStatement();
System.out.println("Connected to the database");
String sql = "SELECT id, navn from ansatt;";
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
oblist.add(new Tabellmodell(rs.getString("id"),rs.getString("navn")));
}
ansattTabell.setItems(oblist);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
FXML:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.TableColumn?>
<?import javafx.scene.control.TableView?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.Pane?>
<?import javafx.scene.text.Font?>
<Pane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/17" xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.example.oppgave.AnsattController">
<children>
<TextField fx:id="innputNavn" layoutX="61.0" layoutY="110.0" />
<TextField fx:id="innputId" layoutX="61.0" layoutY="156.0" />
<Label layoutX="26.0" layoutY="114.0" text="Navn" />
<Label layoutX="26.0" layoutY="160.0" text="Id" />
<Button fx:id="regAnsatt" layoutX="61.0" layoutY="200.0" mnemonicParsing="false" onAction="#regNyAnsatt" text="Registrer" />
<TableView fx:id="ansattTabell" editable="true" layoutX="306.0" layoutY="89.0" prefHeight="200.0" prefWidth="273.0">
<columns>
<TableColumn prefWidth="75.0" text="ID" fx:id="kolid"/>
<TableColumn prefWidth="191.0" text="Navn" fx:id="kolname"/>
</columns>
</TableView>
<Label fx:id="tilbakemelding" layoutX="26.0" layoutY="72.0" />
<Label layoutX="212.0" layoutY="39.0" text="Ansatt">
<font>
<Font size="27.0" />
</font>
</Label>
</children>
</Pane>
I also seem to get a error message when the #FXML variable and the x:id in the fxml is the same
You are trying to set attribute of null object. I think that may be the case. Test it out and reach out to me if it doesn't work.

Pane not showing rectangle grid on scene

package com.gui;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import org.w3c.dom.Text;
import java.net.URL;
import java.util.ResourceBundle;
public class LayoutController {
#FXML
Pane boardPane;
#FXML
Button btnPlayAgain;
#FXML
TextField message;
public void btnPlayAgain(ActionEvent actionEvent) {
message.setText("Testing...");
}
#FXML
public void initialize() {
message.setText("Working");
int w = (int) boardPane.getWidth();
int h = (int) boardPane.getHeight();
int grid = 12;
int scaleW = w / grid;
int scaleH = h / grid + 5;
for (int i = 0; i < w; i += scaleW) {
for (int j = 0; j < h; j += scaleH) {
Rectangle rectangle = new Rectangle(i, j, scaleW, scaleH);
rectangle.setFill(Color.LIGHTYELLOW);
rectangle.setOpacity(2);
rectangle.setStroke(Color.BLACK);
boardPane.getChildren().add(rectangle);
}
}
}
}
My FXML :
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.text.*?>
<AnchorPane minHeight="300" minWidth="300" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/11.0.2" xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.gui.LayoutController">
<Pane prefHeight="50.0" prefWidth="600.0">
<TextField layoutX="100.0" layoutY="14.0" />
<TextField layoutX="375.0" layoutY="14.0" />
<Label layoutX="285.0" layoutY="15.0" text="Player 2" textFill="#000dff">
<font>
<Font name="System Bold" size="17.0" />
</font>
</Label>
<Label alignment="TOP_LEFT" contentDisplay="RIGHT" layoutX="10.0" layoutY="15.0" text="Player 1" textFill="#ee0303">
<font>
<Font name="System Bold" size="17.0" />
</font>
</Label>
</Pane>
<Pane fx:id="boardPane" layoutY="50.0" minHeight="300.0" minWidth="600.0" prefHeight="300.0" prefWidth="600.0" />
<Pane fx:id="paneBottom" layoutY="354.0" prefHeight="42.0" prefWidth="600.0">
<Button fx:id="btnPlayAgain" layoutX="5.0" layoutY="10.0" mnemonicParsing="false" onAction="#btnPlayAgain" text="Play Again" />
<TextField fx:id="message" layoutX="100.0" layoutY="10.0" prefWidth="450.0" editable="false"/>
</Pane>
</AnchorPane>
It should show something like that :
But it is showing something like that :
Please help anybody can help... :)
I want show the gird everytime i run code but nothing is showing in the pane layout I have tried different time but nothing seems to work
your insight to my problem will be very helpful...

JavaFX Responsive TableView

The image is pretty self explanatory. The TableView doesn't auto resize when I resize the window. In C#, I used to do this by using Anchor/Dock properties. How am I supposed to do it in JavaFX? I can't find information about it, probably because Java uses different terms.
table.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.text.*?>
<DialogPane prefHeight="300.0" prefWidth="400.0" xmlns="http://javafx.com/javafx/10.0.2-internal" xmlns:fx="http://javafx.com/fxml/1" fx:controller="gui.TableController">
<header>
<AnchorPane minHeight="50.0" minWidth="0.0" prefHeight="80.0" prefWidth="400.0">
<children>
<HBox alignment="TOP_CENTER" prefHeight="100.0" prefWidth="400.0">
<children>
<Label fx:id="descriptionLabel" alignment="CENTER" contentDisplay="CENTER" prefWidth="400.0" text="Text:" textAlignment="JUSTIFY">
<font>
<Font size="22.0" />
</font>
</Label>
</children>
</HBox>
</children>
</AnchorPane>
</header>
<content>
<AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="200.0" prefWidth="400.0">
<children>
<TableView fx:id="tableView" layoutY="-31.0" prefHeight="252.0" prefWidth="400.0">
<columns>
</columns>
</TableView>
</children>
</AnchorPane>
</content>
</DialogPane>
TableController.java
package gui;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.util.Callback;
import java.sql.ResultSet;
import java.sql.SQLException;
public class TableController {
#FXML
private Label descriptionLabel;
#FXML
private TableView tableView;
public void setTableResultset(String label, ResultSet resultSet) throws SQLException {
ObservableList<ObservableList> data = FXCollections.observableArrayList();
// Columns
for (int i = 0; i < resultSet.getMetaData().getColumnCount(); i++) {
final int j = i;
TableColumn col = new TableColumn(resultSet.getMetaData().getColumnName(i + 1));
col.setCellValueFactory((Callback<TableColumn.CellDataFeatures<ObservableList, String>, ObservableValue<String>>) param -> {
return new SimpleStringProperty(param.getValue().get(j).toString());
});
tableView.getColumns().add(col);
}
// Add records
while (resultSet.next()) {
ObservableList<String> row = FXCollections.observableArrayList();
for (int i = 1; i <= resultSet.getMetaData().getColumnCount(); i++) {
row.add(resultSet.getString(i));
}
data.add(row);
}
tableView.setItems(data);
// Set label text
descriptionLabel.setText(label);
}
}
You need to set AnchorPane's top, bottom, right and left anchors:
<AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="200.0" prefWidth="400.0">
<children>
<TableView fx:id="tableView" layoutY="-31.0" prefHeight="252.0" prefWidth="400.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
<columns>
</columns>
</TableView>
</children>
</AnchorPane>

JavaFX 8 - Layout swapping or similar/equivalent functionality to Qt's StackedWidget?

I've been asked to write a conversion program in JavaFX, but i need to allow the user to set different options depending on the conversion direction.
In reaction to swapping the conversion direction, I need to show two different (unique) sets of controls for options relating to the current direction only.
In one direction I need to display two TextFields, in the other direction, a pair of RadioButtons. I could show both at the same time and just enable/disable when needed, but I'm trying for a less cluttered approach first.
I'm looking for a solution that has similar layout-switching functionality to Qt's StackedWidget that I've used in C++, so i can swap out the TextFields for the RadioButtons and vice versa depending on the conversion direction.
It's important to note that this window has many other options that are common to both directions, so it's only a small part that needs to change according to the conversion direction. Thus I'd prefer it if I could easily access the swapped controls from within the same controller.
I don't want tabs or page numbers as the user controls the direction elsewhere, so TabPane and Pagination are out, unless those undesirable pieces of functionality can be disabled.
I've heard that there's something called a CardLayout in another Java framework (it's in awt if i heard right) which would do the job I want, what's the JavaFX 8 equivalent? Or is there another solution that i should be using instead?
I'm using SceneBuilder so ideally something i can implement in that, but I can use pure code if need be.
You can use any Pane subclass (e.g. a StackPane) and call pane.getChildren().setAll(textFieldDisplay); or pane.getChildren().setAll(radioButtonDisplay); as needed. The different displays can be any kind of Node, but since they hold other controls they would typically also be some subclass of Pane. In the example below I use a GridPane for one and a VBox for the other. In a real application, you might define each one in its own FXML file and load them independently, etc.
Complete example (using FXML):
Main.fxml:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.layout.VBox?>
<?import javafx.scene.layout.StackPane?>
<?import javafx.scene.control.CheckBox?>
<?import javafx.geometry.Insets?>
<?import javafx.scene.control.Button?>
<VBox xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.MainController"
alignment="CENTER">
<padding>
<Insets top="20" left="20" right="20" bottom="20" />
</padding>
<CheckBox text="Show Text Fields" fx:id="showTextFields" VBox.vgrow="NEVER">
<VBox.margin>
<Insets top="10" left="10" right="10" bottom="10"/>
</VBox.margin>
</CheckBox>
<StackPane fx:id="display" VBox.vgrow="ALWAYS" />
<Button text="OK" onAction="#submit" VBox.vgrow="NEVER" />
</VBox>
MainController.java:
package application;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.control.CheckBox;
import javafx.scene.layout.StackPane;
public class MainController {
#FXML
private CheckBox showTextFields ;
#FXML
private StackPane display ;
private Node radioDisplay ;
private Node textFieldDisplay ;
private RadioButtonController radioButtonController ;
private TextFieldController textFieldController ;
public void initialize() throws Exception {
FXMLLoader radioDisplayLoader = new FXMLLoader(getClass().getResource("RadioDisplay.fxml"));
radioDisplay = radioDisplayLoader.load();
radioButtonController = radioDisplayLoader.getController();
FXMLLoader textFieldDisplayLoader = new FXMLLoader(getClass().getResource("TextFieldDisplay.fxml"));
textFieldDisplay = textFieldDisplayLoader.load();
textFieldController = textFieldDisplayLoader.getController();
showTextFields.selectedProperty().addListener((obs, wasSelected, isSelected) -> {
if (isSelected) {
display.getChildren().setAll(textFieldDisplay);
} else {
display.getChildren().setAll(radioDisplay);
}
});
display.getChildren().add(radioDisplay);
}
#FXML
private void submit() {
if (showTextFields.isSelected()) {
System.out.println("Value 1 is "+ textFieldController.getText1());
System.out.println("Value 2 is "+ textFieldController.getText2());
} else {
System.out.println("Chosen value is "+radioButtonController.getSelectedItem());
}
}
}
RadioDisplay.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.layout.VBox?>
<?import javafx.geometry.Insets?>
<?import javafx.scene.control.RadioButton?>
<VBox xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.RadioButtonController"
alignment="TOP_CENTER" spacing="10">
<padding>
<Insets top="10" left="10" right="10" bottom="10"/>
</padding>
<RadioButton text="Choice 1" selected="true" fx:id="choice1"/>
<RadioButton text="Choice 2" fx:id="choice2"/>
</VBox>
RadioButtonController.java:
package application;
import javafx.fxml.FXML;
import javafx.scene.control.RadioButton;
import javafx.scene.control.ToggleGroup;
public class RadioButtonController {
#FXML
private RadioButton choice1 ;
#FXML
private RadioButton choice2 ;
public void initialize() {
ToggleGroup toggleGroup = new ToggleGroup();
choice1.setToggleGroup(toggleGroup);
choice2.setToggleGroup(toggleGroup);
}
public String getSelectedItem() {
if (choice1.isSelected()) {
return "Choice 1";
} else if (choice2.isSelected()) {
return "Choice 2";
} else return "" ;
}
}
TextFieldDisplay.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.layout.ColumnConstraints?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.TextField?>
<GridPane xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.TextFieldController"
hgap="10" vgap="10">
<columnConstraints>
<ColumnConstraints hgrow="NEVER" halignment="RIGHT"/>
<ColumnConstraints hgrow="SOMETIMES" />
</columnConstraints>
<Label text="Value 1:" GridPane.columnIndex="0" GridPane.rowIndex="0"/>
<Label text="Value 2:" GridPane.columnIndex="0" GridPane.rowIndex="1"/>
<TextField fx:id="textField1" GridPane.columnIndex="1" GridPane.rowIndex="0"/>
<TextField fx:id="textField2" GridPane.columnIndex="1" GridPane.rowIndex="1"/>
</GridPane>
TextFieldController.java:
package application;
import javafx.fxml.FXML;
import javafx.scene.control.TextField;
public class TextFieldController {
#FXML
private TextField textField1 ;
#FXML
private TextField textField2 ;
public String getText1() {
return textField1.getText() ;
}
public String getText2() {
return textField2.getText();
}
}
Main.java:
package application;
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.VBox;
import javafx.fxml.FXMLLoader;
public class Main extends Application {
#Override
public void start(Stage primaryStage) throws Exception {
VBox root = (VBox)FXMLLoader.load(getClass().getResource("Main.fxml"));
Scene scene = new Scene(root,400,400);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
All the FXML files are in the same package (application) as the .java files.
Update
If you prefer not to "modularize" it to this extent, you can put everything in a single FXML with a single controller. In that case, Main.fxml looks like
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.layout.VBox?>
<?import javafx.scene.layout.StackPane?>
<?import javafx.scene.control.CheckBox?>
<?import javafx.geometry.Insets?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.RadioButton?>
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.layout.ColumnConstraints?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.TextField?>
<VBox xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.MainController"
alignment="CENTER">
<padding>
<Insets top="20" left="20" right="20" bottom="20" />
</padding>
<CheckBox text="Show Text Fields" fx:id="showTextFields" VBox.vgrow="NEVER">
<VBox.margin>
<Insets top="10" left="10" right="10" bottom="10"/>
</VBox.margin>
</CheckBox>
<StackPane fx:id="display" VBox.vgrow="ALWAYS">
<VBox fx:id="radioDisplay" alignment="TOP_CENTER" spacing="10">
<padding>
<Insets top="10" left="10" right="10" bottom="10" />
</padding>
<RadioButton text="Choice 1" selected="true" fx:id="choice1" />
<RadioButton text="Choice 2" fx:id="choice2" />
</VBox>
<fx:define>
<GridPane fx:id="textFieldDisplay" hgap="10" vgap="10">
<columnConstraints>
<ColumnConstraints hgrow="NEVER" halignment="RIGHT" />
<ColumnConstraints hgrow="SOMETIMES" />
</columnConstraints>
<Label text="Value 1:" GridPane.columnIndex="0"
GridPane.rowIndex="0" />
<Label text="Value 2:" GridPane.columnIndex="0"
GridPane.rowIndex="1" />
<TextField fx:id="textField1" GridPane.columnIndex="1"
GridPane.rowIndex="0" />
<TextField fx:id="textField2" GridPane.columnIndex="1"
GridPane.rowIndex="1" />
</GridPane>
</fx:define>
</StackPane>
<Button text="OK" onAction="#submit" VBox.vgrow="NEVER" />
</VBox>
and the corresponding controller is
package application;
import javafx.fxml.FXML;
import javafx.scene.Node;
import javafx.scene.control.CheckBox;
import javafx.scene.control.RadioButton;
import javafx.scene.control.TextField;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.StackPane;
public class MainController {
#FXML
private CheckBox showTextFields ;
#FXML
private StackPane display ;
#FXML
private Node radioDisplay ;
#FXML
private Node textFieldDisplay ;
#FXML
private TextField textField1 ;
#FXML
private TextField textField2 ;
#FXML
private RadioButton choice1 ;
#FXML
private RadioButton choice2 ;
public void initialize() throws Exception {
showTextFields.selectedProperty().addListener((obs, wasSelected, isSelected) -> {
if (isSelected) {
display.getChildren().setAll(textFieldDisplay);
} else {
display.getChildren().setAll(radioDisplay);
}
});
ToggleGroup toggleGroup = new ToggleGroup();
choice1.setToggleGroup(toggleGroup);
choice2.setToggleGroup(toggleGroup);
}
#FXML
private void submit() {
if (showTextFields.isSelected()) {
System.out.println("Value 1 is "+ textField1.getText());
System.out.println("Value 2 is "+ textField2.getText());
} else {
String chosenValue ;
if (choice1.isSelected()) {
chosenValue = "Choice 1";
} else if (choice2.isSelected()) {
chosenValue = "Choice 2";
} else {
chosenValue
= "None";
}
System.out.println("Chosen value is "+chosenValue);
}
}
}
(and in this case, remove the other two FXML files and their controllers).

JavaFx won't schange Scenes

package Data_Project;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import java.io.IOException;
public class Main extends Application {
public Stage window;
#Override
public void start(Stage primaryStage) throws Exception{
window = primaryStage;
//Scene1
Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
Parent root1 = FXMLLoader.load(getClass().getResource("Admin.fxml"));
Controller a1 = new Controller();
a1.getSubmitButton().setOnAction(e -> {
window.setScene(new Scene(root1,500,500));
});
window.setTitle("Log in");
window.setScene(new Scene(root,500,500));
window.show();
}
public static void main(String[] args) throws IOException {
launch(args);
}
}
Hey there, im getting error with this code, I can't figure out what's wrong.
Exception in Application start method Exception in thread "main"
java.lang.RuntimeException: Exception in Application start method at
com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:875)
at
com.sun.javafx.application.LauncherImpl.lambda$launchApplication$147(LauncherImpl.java:157)
at
com.sun.javafx.application.LauncherImpl$$Lambda$1/989110044.run(Unknown
Source) at java.lang.Thread.run(Thread.java:745) Caused by:
java.lang.NullPointerException at
Data_Project.Main.start(Main.java:20)
XML:
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<GridPane alignment="center" hgap="10" vgap="10" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="Data_Project.Controller">
<children>
<Label text="Username" GridPane.columnIndex="1" GridPane.rowIndex="1" />
<TextField fx:id="userField" GridPane.columnIndex="2" GridPane.rowIndex="1" />
<Label text="Password" GridPane.columnIndex="1" GridPane.rowIndex="3" />
<PasswordField fx:id="passField" GridPane.columnIndex="2" GridPane.columnSpan="1" GridPane.rowIndex="3" />
<Button fx:id="submitButton" onAction="#submitForm" text="Log in" GridPane.columnIndex="2" GridPane.columnSpan="2" GridPane.rowIndex="4" />
<Label fx:id="errorLabel" textFill="#c30808" GridPane.columnIndex="2" GridPane.columnSpan="2" GridPane.rowIndex="6" />
</children>
</GridPane>
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<GridPane alignment="center" hgap="10" vgap="10" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="Data_Project.Admin">
<children>
<Label text="Username" GridPane.columnIndex="1" GridPane.rowIndex="1" />
<TextField fx:id="userField" GridPane.columnIndex="2" GridPane.rowIndex="1" />
<Label text="Password" GridPane.columnIndex="1" GridPane.rowIndex="3" />
<PasswordField fx:id="passField" GridPane.columnIndex="2" GridPane.columnSpan="1" GridPane.rowIndex="3" />
<Button fx:id="submitButton" text="Log in" GridPane.columnIndex="2" GridPane.columnSpan="2" GridPane.rowIndex="4" />
<Label fx:id="errorLabel" textFill="#c30808" GridPane.columnIndex="2" GridPane.columnSpan="2" GridPane.rowIndex="6" />
</children>
</GridPane>
The XML are both Different Files, but shown here as 1 file, they have the same attributes and all because it was for testing the scene switcher, but for some reason i can't get it to work!
Controller class:
package Data_Project;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.Scene;
import javafx.scene.control.*;
public class Controller{
Scene window;
#FXML Button submitButton;
#FXML TextField userField;
#FXML PasswordField passField;
#FXML Label errorLabel;
public void submitForm(ActionEvent actionEvent) {
authorizedUser user = new authorizedUser();
if(!user.checkCredentials(userField.getText(), passField.getText()))
{
errorLabel.setText("Invalid credentials");
}
}
public Button getSubmitButton() {
return submitButton;
}
}
Admin:
package Data_Project;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.Scene;
import javafx.scene.control.*;
public class Admin{
Scene window;
#FXML Button submitButton;
#FXML TextField userField;
#FXML PasswordField passField;
#FXML Label errorLabel;
public Button getSubmitButton() {
return submitButton;
}
}
The FXMLLoader parses the FXML file, creates an instance of the controller class (if one is specified) and injects any #FXML-annotated fields into that controller instance.
If you create your own controller instance, as you do with
Controller a1 = new Controller();
then the FXMLLoader knows nothing of that instance (how would it?) and so the #FXML-annotated fields are not initialized. Hence when you call
a1.getSubmitButton()
it returns null and so you get a NullPointerException.
To fix this, replace
Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
and
Controller a1 = new Controller();
with
FXMLLoader loader = new FXMLLoader(getClass().getResource("sample.fxml"));
Parent root = loader.load();
Controller a1 = loader.getController();
This gives you a reference to the controller instance that the FXMLLoader created, so it has its #FXML-annotated fields properly initialized.

Categories

Resources