fxml tableview just showing blank rows - java

I have a FXML file that looks like this:
<GridPane alignment="CENTER" hgap="10.0" vgap="10.0"
xmlns:fx="http://javafx.com/fxml"
fx:controller="GUI.Controller">
<padding>
<Insets bottom="10.0" left="10.0" right="10.0" top="10.0" />
</padding>
<HBox spacing="10" alignment="bottom_right"
GridPane.columnIndex="1" GridPane.rowIndex="4">
<Button text="Sign In"
onAction="#handleSubmitButtonAction"/>
</HBox>
<TableView fx:id="tableView" GridPane.columnIndex="0" GridPane.rowIndex="0">
<columns>
<TableColumn fx:id="nameColumn" text="Event Name">
</TableColumn>
</columns>
</TableView>
and a controller class like this:
public class Controller implements Initializable {
#FXML
private TableView<String> tableView;
#FXML
private TableColumn<String, String> nameColumn;
#FXML
private ObservableList <String> dataArray;
#Override
public void initialize(URL location, ResourceBundle resources) {
dataArray = FXCollections.observableArrayList();
nameColumn.setCellValueFactory(
new PropertyValueFactory<String, String>("nameColumn")
);
dataArray.add("hello");
dataArray.add("goodbye");
tableView.setItems(dataArray);
}
When I run this, I get two columns(not sure why - one is called "Event Name" and the other is blank) and two rows, but the rows are blank. You can click on the rows, but there is no data in them. When I remove the "hello" entry or the "goodbye" entry from the code, the table just displays one blank row instead of two.
I'm new to Java and not exactly sure why this is happening. Why are they rows showing up, but the data isn't displaying?

The best way to use table is use class for representing data in table. In your example I changed String to TableModel where you have one PropertyString name greetings. Now you can easy use this class to show data in tabe.
Controller:
public class Controller implements Initializable {
#FXML private TableView<TableModel> tableView;
#FXML private TableColumn<TableModel, String> nameColumn;
#FXML private ObservableList<TableModel> dataArray;
#Override public void initialize(URL location, ResourceBundle resources) {
//add data to Observable List
dataArray = FXCollections.observableArrayList(new TableModel("hello"), new TableModel("goodbye"));
//crete one column, name "greetings" is the same name property which is in TableModel
nameColumn.setCellValueFactory(new PropertyValueFactory<TableModel, String>("greetings"));
tableView.setItems(dataArray);
}
public static class TableModel {
StringProperty greetings = new SimpleStringProperty();
public TableModel(String greetings) {
this.greetings = new SimpleStringProperty(greetings);
}
public String getGreetings() {
return greetings.get();
}
public StringProperty greetingsProperty() {
return greetings;
}
public void setGreetings(String greetings) {
this.greetings.set(greetings);
}
}
}
You must add this code to resolve problem with two columns.
<columnResizePolicy>
<TableView fx:constant="CONSTRAINED_RESIZE_POLICY"/>
</columnResizePolicy>
Here is your FXML with small changes.
<GridPane alignment="CENTER" hgap="10.0" vgap="10.0" xmlns:fx="http://javafx.com/fxml" fx:controller="GUI.Controller">
<padding>
<Insets bottom="10.0" left="10.0" right="10.0" top="10.0"/>
</padding>
<TableView fx:id="tableView" GridPane.columnIndex="0" GridPane.rowIndex="0">
<columnResizePolicy>
<TableView fx:constant="CONSTRAINED_RESIZE_POLICY"/>
</columnResizePolicy>
<columns>
<TableColumn fx:id="nameColumn" text="Event Name"/>
</columns>
</TableView>
<HBox spacing="10" alignment="bottom_right" GridPane.columnIndex="1" GridPane.rowIndex="1">
<Button text="Sign In" onAction="#handleSubmitButtonAction"/>
</HBox>
</GridPane>

Related

JavaFx TableView doesnt show data

I know there are many questions about this, but the answers didn't solve my problem.
I have a TableView with 4 columns. The data is read out of a txt file.
In the initialize method from the Controller the CellValueFactory is set, and another method is called, which reads the Data from the file and creates an observableList of the model.
Then the list is added to the items of the table, but no data is displayed, and no placeholder is there. Does anyone know what is wrong?
Controller class
#FXML
private TableView<Data> dataTable;
#FXML
private TableColumn<Data, String> dataType;
#FXML
private TableColumn<Data, String> dataName;
#FXML
private TableColumn<Data, String> dataDate;
#FXML
private TableColumn<Data, String> dataInformation;
#FXML
public void initialize() {
dataType.setCellValueFactory(value -> new SimpleStringProperty(value.getValue().getDataType()));
dataName.setCellValueFactory(value -> new SimpleStringProperty(value.getValue().getDataName()));
dataDate.setCellValueFactory(value -> new SimpleStringProperty(value.getValue().getDataDate()));
dataInformation.setCellValueFactory(value -> new SimpleStringProperty(value.getValue().getDataInformation()));
initData();
}
private void initData() {
ArrayList<Data> data = new ArrayList<>();
try {
Path filePath = Paths.get("src/main/resources/kl/fla/decrypted.txt");
if (filePath.toFile().exists()) {
data = (ArrayList<Data>) Files.readAllLines(filePath, StandardCharsets.UTF_8).stream()
.map(Data::new).collect(Collectors.toList());
}
} catch (Exception e) {
e.printStackTrace();
}
dataTable.setItems(FXCollections.observableArrayList(data));
dataTable.refresh();
}
FXML File
<Pane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="720.0"
prefWidth="1080.0" xmlns="http://javafx.com/javafx/18" xmlns:fx="http://javafx.com/fxml/1" fx:controller="kl.fla.controller.TableController"
>
<children>
<Label alignment="CENTER" layoutX="393.0" layoutY="34.0" prefHeight="70.0" prefWidth="295.0" text="Hidden Gate">
<font>
<Font size="48.0" />
</font>
</Label>
<TableView fx:id="dataTable" fixedCellSize="1.0" layoutX="36.0" layoutY="141.0" prefHeight="439.0" prefWidth="840.0">
<columns>
<TableColumn fx:id="dataType" prefWidth="135.0" resizable="false" text="Datatype" />
<TableColumn fx:id="dataName" minWidth="4.0" prefWidth="135.0" resizable="false" text="Name" />
<TableColumn fx:id="dataDate" prefWidth="135.0" resizable="false" text="Date" />
<TableColumn fx:id="dataInformation" minWidth="0.0" prefWidth="285.0" resizable="false" text="Information" />
</columns>
</TableView>
</children>
</Pane>
Screenshot of the empty TableView
The data are (probably) there; you just can’t see them because you have constrained every row to be just one pixel high:
fixedCellSize="1.0"
Remove that attribute and just use the default setting, and it should work (assuming there are no other errors in code you haven’t posted).

FXML displaying windows in other tabs

I have problem with displaying windows in my program. In the first window it is necessary to write in username and password and choose one option (Admin/Student). Then click button 'Login'. Additionaly I added also another label with message (if log data are good or not). But if I click this button, nothing happens. I don't know why.
LoginApp.java
public class LoginController implements Initializable {
LoginModel loginModel = new LoginModel();
#FXML
private AnchorPane ap;
#FXML
private Label loginstatus;
#FXML
private Label dbstatus;
#FXML
private TextField username;
#FXML
private PasswordField password;
#FXML
private ComboBox<option> combobox;
#FXML
private Button loginbutton;
public void initialize(URL url, ResourceBundle rb) {
if (this.loginModel.isDatabaseConnected()) {
this.dbstatus.setText("Connected to Database");
} else {
this.dbstatus.setText("Not connected to Database");
}
this.combobox.setItems(FXCollections.observableArrayList(option.values()));
}
#FXML
public void login(ActionEvent event) {
//combobox.setEditable(false);
try {
if (this.loginModel.isLogin(this.username.getText(), this.password.getText(),
((option) this.combobox.getValue()).toString())) {
Stage stage = (Stage) this.loginbutton.getScene().getWindow();
stage.close();
switch (((option) this.combobox.getValue()).toString()) {
case "Student":
studentLogin();
break;
case "Admin":
adminLogin();
System.out.println("Dadasd");
break;
}
} if (this.loginModel.isLogin(this.username.getText(), this.password.getText(),
((option) this.combobox.getValue()).toString())) {
this.loginstatus.setText("Connected");
} else
{
this.loginstatus.setText("Denied");
}
} catch (Exception localException) {
}
try {
this.username.setText("");
this.password.setText("");
}catch (Exception localException){
}
}
public void studentLogin() {
//combobox.setEditable(false);
try {
Stage userStage = new Stage();
FXMLLoader loader = new FXMLLoader();
Parent root = (Parent) loader.load(getClass().getResource("/students/studentFXML.fxml").openStream());
StudentController studentController = (StudentController) loader.getController();
Scene scene = new Scene(root);
userStage.setScene(scene);
userStage.setTitle("Student Board");
userStage.setResizable(false);
userStage.show();
} catch (IOException ex) {
ex.printStackTrace();
}
}
public void adminLogin() {
//combobox.setEditable(false);
try {
Stage adminStage = new Stage();
FXMLLoader adminLoader = new FXMLLoader();
Pane adminroot = (Pane) adminLoader.load(getClass().getResource("/admin/tabs/admin.fxml").openStream());
AdminController adminController = (AdminController) adminLoader.getController();
Scene scene = new Scene(adminroot);
adminStage.setScene(scene);
adminStage.setTitle("Admin Board");
adminStage.setResizable(false);
adminStage.show();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
login.fxml
<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="350.0" prefWidth="350.0" xmlns="http://javafx.com/javafx/8.0.141" xmlns:fx="http://javafx.com/fxml/1" fx:controller="loginapp.LoginController">
<children>
<Label layoutX="14.0" layoutY="14.0" prefHeight="17.0" prefWidth="86.0" text="DB status" />
<Label fx:id="dbstatus" layoutX="101.0" layoutY="14.0" prefHeight="17.0" prefWidth="216.0" />
<Label fx:id="loginstatus" layoutX="14.0" layoutY="217.0" prefHeight="17.0" prefWidth="79.0" />
<TextField fx:id="username" layoutX="101.0" layoutY="79.0" prefHeight="25.0" prefWidth="216.0" promptText="user name" />
<Label layoutX="14.0" layoutY="83.0" prefHeight="17.0" prefWidth="79.0" text="UserName" />
<Label layoutX="14.0" layoutY="124.0" prefHeight="17.0" prefWidth="79.0" text="Password" />
<PasswordField fx:id="password" layoutX="101.0" layoutY="120.0" prefHeight="25.0" prefWidth="216.0" promptText="password" />
<ComboBox fx:id="combobox" layoutX="101.0" layoutY="169.0" prefHeight="25.0" prefWidth="216.0" promptText="Admin/Student" />
<Button fx:id="loginbutton" layoutX="100.0" layoutY="213.0" mnemonicParsing="false" onAction="#login" prefHeight="25.0" prefWidth="216.0" text="Login" />
</children>
</AnchorPane>
StudentController.java
public class StudentController implements Initializable {
#FXML
private TextField firstname;
#FXML
private TextField lastname;
#FXML
private TextField email;
#FXML
private DatePicker dob;
#FXML
private TableView<StudentData> studenttable;
#FXML
private TableColumn<StudentData, String> firstnamecolumn;
#FXML
private TableColumn<StudentData, String> lastnamecolumn;
#FXML
private TableColumn<StudentData, String> emailcolumn;
#FXML
private TableColumn<StudentData, String> dobcolumn;
private ObservableList<StudentData> data;
private dbConnection dc;
private String sql = "SELECT * FROM students";
public void initialize(URL url, ResourceBundle rb) {
this.dc = new dbConnection();
}
#FXML
private void loadStudentData(ActionEvent event) throws SQLException {
try {
Connection conn = dbConnection.getConnection();
this.data = FXCollections.observableArrayList();
ResultSet rs = conn.createStatement().executeQuery(sql);
while (rs.next()) {
this.data.add(new StudentData(rs.getString(1), rs.getString(2), rs.getString(3),
rs.getString(4))); }
} catch (SQLException ex) {
System.err.println("Error : " + ex);
}
this.firstnamecolumn.setCellValueFactory(new PropertyValueFactory<StudentData, String>("firstName"));
this.lastnamecolumn.setCellValueFactory(new PropertyValueFactory<StudentData, String>("lastName"));
this.emailcolumn.setCellValueFactory(new PropertyValueFactory<StudentData, String>("email"));
this.dobcolumn.setCellValueFactory(new PropertyValueFactory<StudentData, String>("DOB"));
this.studenttable.setItems(null);
this.studenttable.setItems(this.data);
}
#FXML
private void addStudent (ActionEvent event) {
String sqlAdd = "INSERT INTO students (firstName, lastName, email, DOB) VALUES (?, ?, ?, ?)";
try {
Connection conn = dbConnection.getConnection();
PreparedStatement stmt = conn.prepareStatement(sqlAdd);
stmt.setString(2, this.firstname.getText());
stmt.setString(3, this.lastname.getText());
stmt.setString(4, this.email.getText());
stmt.setString(5, this.dob.getEditor().getText());
stmt.execute();
stmt.close();
}catch (SQLException ex) {
System.err.println("Error :" + ex);
}
}
#FXML
private void clearFields(ActionEvent event) {
this.firstname.setText("");
this.lastname.setText("");
this.email.setText("");
this.dob.setValue(null);
}
}
studentFXML.fxml
<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="360.0"
prefWidth="640.0" xmlns="http://javafx.com/javafx/8.0.141" xmlns:fx="http://javafx.com/fxml/1"
fx:controller="students.StudentController">
<children>
<TabPane prefHeight="360.0" prefWidth="640.0" tabClosingPolicy="UNAVAILABLE">
<tabs>
<Tab text="Student">
<content>
<AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="360.0" prefWidth="640.0">
<children>
<HBox layoutX="156.0" prefHeight="330.0" prefWidth="490.0">
<children>
<TableView fx:id="studenttable" prefHeight="330.0" prefWidth="490.0">
<columns>
<TableColumn fx:id="idcolumn" prefWidth="75.0" text="ID"/>
<TableColumn fx:id="firstnamecolumn" prefWidth="106.0"
text="First Name"/>
<TableColumn fx:id="lastnamecolumn" prefWidth="112.0" text="Last Name"/>
<TableColumn fx:id="emailcolumn" prefWidth="108.0" text="Email"/>
<TableColumn fx:id="dobcolumn" minWidth="0.0" prefWidth="82.0"
text="DOB"/>
</columns>
</TableView>
</children>
</HBox>
<VBox prefHeight="337.0" prefWidth="159.0">
<children>
<Label prefHeight="19.0" prefWidth="160.0" text="Add student">
<padding>
<Insets left="10.0"/>
</padding>
<VBox.margin>
<Insets/>
</VBox.margin>
</Label>
<TextField fx:id="id">
<VBox.margin>
<Insets left="10.0" right="10.0" top="10.0"/>
</VBox.margin>
</TextField>
<TextField fx:id="firstname" layoutX="10.0" layoutY="29.0"
promptText="First Name">
<VBox.margin>
<Insets left="10.0" right="10.0"/>
</VBox.margin>
</TextField>
<TextField fx:id="lastname" layoutX="10.0" layoutY="54.0"
promptText="Last Name">
<VBox.margin>
<Insets left="10.0" right="10.0"/>
</VBox.margin>
</TextField>
<TextField fx:id="email" layoutX="10.0" layoutY="54.0" promptText="Email">
<VBox.margin>
<Insets left="10.0" right="10.0"/>
</VBox.margin>
</TextField>
<DatePicker fx:id="dob" prefWidth="200.0">
<VBox.margin>
<Insets left="10.0" right="10.0"/>
</VBox.margin>
</DatePicker>
<Button mnemonicParsing="false" onAction="#addStudent" prefHeight="17.0"
prefWidth="140.0" text="Add Data">
<VBox.margin>
<Insets left="10.0"/>
</VBox.margin>
</Button>
<Button layoutX="20.0" layoutY="164.0" mnemonicParsing="false"
onAction="#clearFields" prefHeight="17.0" prefWidth="140.0"
text="Clear Form">
<VBox.margin>
<Insets left="10.0"/>
</VBox.margin>
</Button>
<Button layoutX="20.0" layoutY="189.0" mnemonicParsing="false"
onAction="#loadStudentData" prefHeight="17.0" prefWidth="140.0"
text="Load Form">
<VBox.margin>
<Insets left="10.0"/>
</VBox.margin>
</Button>
<Button mnemonicParsing="false" prefHeight="25.0" prefWidth="152.0"
text="Delete Data">
<VBox.margin>
<Insets left="10.0" right="10.0"/>
</VBox.margin>
</Button>
</children>
</VBox>
</children>
</AnchorPane>
</content>
</Tab>
</tabs>
</TabPane>
</children>
option.java
public enum option {
Admin, Student;
private option() {}
public String value() {
return name();
}
public static option fromvalue (String v) {
return valueOf(v);
}
}

Dynamically added view wont fit Pane

I want to make a application with a menu on the left and the view on the right. I have different fxml file. 1 main, and multiple for the view.
Right now I load different view but the view on right doesn't his parent.
Main view
<GridPane
xmlns="http://javafx.com/javafx/8.0.112"
xmlns:fx="http://javafx.com/fxml/1"
fx:controller="controller.Controller">
<columnConstraints>
<ColumnConstraints percentWidth="30.0" />
<ColumnConstraints percentWidth="70.0" />
</columnConstraints>
<rowConstraints>
<RowConstraints />
</rowConstraints>
<children>
<GridPane maxWidth="Infinity" GridPane.columnIndex="0" GridPane.rowIndex="0">
<columnConstraints>
<ColumnConstraints percentWidth="100.0" />
</columnConstraints>
<rowConstraints>
<RowConstraints />
<RowConstraints />
<RowConstraints />
<RowConstraints />
<RowConstraints />
</rowConstraints>
<children>
<Button fx:id="devices" maxWidth="Infinity" mnemonicParsing="false" text="Devices" GridPane.columnIndex="0" GridPane.rowIndex="0" />
<Button fx:id="inventory" maxWidth="Infinity" mnemonicParsing="false" text="Inventory" GridPane.columnIndex="0" GridPane.rowIndex="1" />
</children>
</GridPane>
<Pane
fx:id="container"
minWidth="Infinity"
maxWidth="Infinity"
GridPane.hgrow="ALWAYS"
GridPane.vgrow="ALWAYS"
GridPane.columnIndex="1"
GridPane.columnSpan="1"
GridPane.rowIndex="0">
</Pane>
</children>
</GridPane>
Custom view load in container
<GridPane
xmlns="http://javafx.com/javafx/8.0.112"
xmlns:fx="http://javafx.com/fxml/1"
fx:controller="controller.DevicesController"
GridPane.hgrow="ALWAYS"
GridPane.vgrow="ALWAYS">
<children>
<TableView
GridPane.columnIndex="0"
GridPane.columnSpan="1"
GridPane.hgrow="ALWAYS"
GridPane.vgrow="ALWAYS"
GridPane.rowIndex="0">
<columns>
<TableColumn text="Devices" />
<TableColumn text="C2" />
</columns>
</TableView>
</children>
</GridPane>
Current form
Controller
public class Controller implements Initializable {
#FXML private Pane container;
#FXML private Button devices;
#FXML private Button inventory;
private HashMap<Views, Node> views;
private enum Views {
DEVICES,
INVENTORY
}
#Override
public void initialize(URL location, ResourceBundle resources) {
try {
views = new HashMap<>();
views.put(Views.DEVICES, FXMLLoader.load(getClass().getResource("../view/" + "view-devices.fxml")));
views.put(Views.INVENTORY, FXMLLoader.load(getClass().getResource("../view/" + "view-inventory.fxml")));
devices.setOnMouseClicked(v -> load(Views.DEVICES));
inventory.setOnMouseClicked(v -> load(Views.INVENTORY));
} catch (IOException e) {
e.printStackTrace();
}
}
public void load(Views view){
if (views.containsKey(view)) {
Node newView = views.get(view);
if (!container.getChildren().contains(newView)) {
container.getChildren().add(newView);
} else {
newView.resize(container.getMaxWidth(), container.getMaxHeight());
newView.toFront();
}
} else {
System.out.println("Error: key not found in map");
}
}
}
I want to the right view to fit the container.
The Pane you are using for the container for the right side of the display performs no layout, so it cannot make the content fill the available space (no matter what settings you use).
Use a BorderPane for the container instead:
<BorderPane
fx:id="container"
GridPane.hgrow="ALWAYS"
GridPane.vgrow="ALWAYS"
GridPane.columnIndex="1"
GridPane.columnSpan="1"
GridPane.rowIndex="0">
</BorderPane>
and then in the controller you can simply set the new content as the center each time:
public class Controller implements Initializable {
#FXML private BorderPane container;
// ...
public void load(Views view){
if (views.containsKey(view)) {
Node newView = views.get(view);
container.setCenter(newView);
} else {
System.out.println("Error: key not found in map");
}
}
}

Values get swapped in table column when trying to filter Observable list by Applying filterlist and sortedlist

I'm creating a gate pass software which uses Table view to directly add data to MYSQL database, I added a search textField to search entries from Tutorial
and whenever I search using that textField everything works fine but in back ground these errors appears
"C:\Program Files\Java\jdk1.8.0_102\bin\java" -Didea.launcher.port=7537 "-Didea.launcher.bin.path=C:\Program Files (x86)\JetBrains\IntelliJ IDEA 2016.3.4\bin" -Dfile.encoding=UTF-8 -classpath "C:\Program Files\Java\jdk1.8.0_102\jre\lib\charsets.jar;C:\Program Files\Java\jdk1.8.0_102\jre\lib\deploy.jar;C:\Program Files\Java\jdk1.8.0_102\jre\lib\ext\access-bridge-64.jar;C:\Program Files\Java\jdk1.8.0_102\jre\lib\ext\cldrdata.jar;C:\Program Files\Java\jdk1.8.0_102\jre\lib\ext\dnsns.jar;C:\Program Files\Java\jdk1.8.0_102\jre\lib\ext\jaccess.jar;C:\Program Files\Java\jdk1.8.0_102\jre\lib\ext\jfxrt.jar;C:\Program Files\Java\jdk1.8.0_102\jre\lib\ext\localedata.jar;C:\Program Files\Java\jdk1.8.0_102\jre\lib\ext\nashorn.jar;C:\Program Files\Java\jdk1.8.0_102\jre\lib\ext\sunec.jar;C:\Program Files\Java\jdk1.8.0_102\jre\lib\ext\sunjce_provider.jar;C:\Program Files\Java\jdk1.8.0_102\jre\lib\ext\sunmscapi.jar;C:\Program Files\Java\jdk1.8.0_102\jre\lib\ext\sunpkcs11.jar;C:\Program Files\Java\jdk1.8.0_102\jre\lib\ext\zipfs.jar;C:\Program Files\Java\jdk1.8.0_102\jre\lib\javaws.jar;C:\Program Files\Java\jdk1.8.0_102\jre\lib\jce.jar;C:\Program Files\Java\jdk1.8.0_102\jre\lib\jfr.jar;C:\Program Files\Java\jdk1.8.0_102\jre\lib\jfxswt.jar;C:\Program Files\Java\jdk1.8.0_102\jre\lib\jsse.jar;C:\Program Files\Java\jdk1.8.0_102\jre\lib\management-agent.jar;C:\Program Files\Java\jdk1.8.0_102\jre\lib\plugin.jar;C:\Program Files\Java\jdk1.8.0_102\jre\lib\resources.jar;C:\Program Files\Java\jdk1.8.0_102\jre\lib\rt.jar;C:\Program Files (x86)\MySQL\Connector.J 5.1\mysql-connector-java-5.1.40-bin.jar;C:\Users\Suraj\IdeaProjects\DemoFinal\out\production\DemoFinal;C:\Program Files (x86)\JetBrains\IntelliJ IDEA 2016.3.4\lib\idea_rt.jar" com.intellij.rt.execution.application.AppMain sample.Main
Exception in thread "JavaFX Application Thread" java.lang.IllegalArgumentException: argument type mismatch
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at sun.reflect.misc.Trampoline.invoke(MethodUtil.java:71)
at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at sun.reflect.misc.MethodUtil.invoke(MethodUtil.java:275)
at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1769)
at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1657)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:389)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleKeyEvent(GlassViewEventHandler.java:246)
at com.sun.glass.ui.View.handleKeyEvent(View.java:546)
at com.sun.glass.ui.View.notifyKey(View.java:966)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
at java.lang.Thread.run(Thread.java:745)
when ever i press a key for search every thing works great , but after every keypress these errors gets generated.
And also after search my column values gets swapped Like I have two columns one for address and other for email, after search they start to show each others data inside them their data gets swapped.
package sample;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.collections.transformation.SortedList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import java.net.URL;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Objects;
import java.util.ResourceBundle;
import java.util.function.Predicate;
public class DataController implements Initializable {
Config config = new Config();
Connection connection = DatabaseConnection.getConnection();
int ids;
#FXML
private TextArea Address;
#FXML
private Label LabelFilter;
#FXML
private TextField TextFiledFilter;
#FXML
private TextField Lname;
#FXML
private TextField PhoneNo;
#FXML
private Button btnAdd;
#FXML
private TableColumn<EntryData, String> firstname;
#FXML
private TableColumn<EntryData, String> address;
#FXML
private TableColumn<?, ?> Timee;
#FXML
private TableColumn<EntryData, String> emailid;
#FXML
private TableColumn<EntryData, Double> phoneno;
#FXML
private TableColumn<EntryData, String> lastname;
#FXML
private TableColumn<EntryData, Integer> id;
#FXML
private TableColumn<?, ?> Datee;
#FXML
private TextField mailId;
#FXML
private Menu menuFile;
#FXML
private MenuBar MenuBar;
#FXML
private MenuItem MenuItemFilter;
#FXML
private TextField Fname;
#FXML
private TableView TableID;
ObservableList<EntryData> list = FXCollections.observableArrayList();
ObservableList<EntryData> FilterData = FXCollections.observableArrayList();
#FXML
void addBtnAction(ActionEvent event) throws SQLException {
String query = "INSERT INTO DemoFinal(id,name,lastname,phone_no,email_id,Address) Values(?,?,?,?,?,?)";
PreparedStatement statement = connection.prepareStatement(query);
statement.setInt(1, ++ids);
statement.setString(2, Fname.getText());
statement.setString(3, Lname.getText());
statement.setDouble(4, Double.parseDouble(PhoneNo.getText()));
statement.setString(5, mailId.getText());
statement.setString(6, Address.getText());
statement.execute();
Fname.clear();
Lname.clear();
mailId.clear();
Address.clear();
PhoneNo.clear();
TableID.getItems().addAll(list);
statement.close();
}
public DataController() throws Exception {
}
public void factorySettings() {
id.setCellValueFactory(new PropertyValueFactory<EntryData, Integer>("id"));
firstname.setCellValueFactory(new PropertyValueFactory<EntryData, String>("name"));
lastname.setCellValueFactory(new PropertyValueFactory<EntryData, String>("lastname"));
phoneno.setCellValueFactory(new PropertyValueFactory<EntryData, Double>("phone_no"));
emailid.setCellValueFactory(new PropertyValueFactory<EntryData, String>("email"));
address.setCellValueFactory(new PropertyValueFactory<EntryData, String>("address"));
}
#Override
public void initialize(URL location, ResourceBundle resources) {
if (connection != null) {
try {
DatabaseConnection.getConnection();
update();
} catch (Exception e) {
e.printStackTrace();
}
} else {
config.alert(Alert.AlertType.ERROR, "Database Server May be Down Check Logs");
}
FilteredList <EntryData> filteredList= new FilteredList<EntryData>(list ,e-> true);
TextFiledFilter.textProperty().addListener((observable, oldValue, newValue) ->{
filteredList.setPredicate((Predicate<?super EntryData>) EntryData->{
if(newValue==null||newValue.isEmpty()){
return true;
}
String iid= String.valueOf(EntryData.getId());
String tolowercase= newValue.toLowerCase();
if (EntryData.getName().toLowerCase().contains(tolowercase)){
return true;
}
else if(EntryData.getLastname().contains(tolowercase)){
return true;
}
else if (EntryData.getEmail().toLowerCase().contains(tolowercase)){
return true;
}
else if(EntryData.getAddress().toLowerCase().contains(tolowercase)){
return true;
}
else if(String.valueOf(EntryData.getId()).contains(newValue)) {
return true;
}
else if (String.valueOf(EntryData.getPhone_no()).contains(newValue)){
return true;
}
return false;
} );
});
SortedList<EntryData> sortedList= new SortedList<>(filteredList);
sortedList.comparatorProperty().bind(TableID.comparatorProperty());
TableID.setItems(sortedList);
}
public void update() throws SQLException {
factorySettings();
ResultSet resultSet = null;
try {
resultSet = connection.createStatement().executeQuery("SELECT * FROM DemoFinal");
} catch (SQLException e) {
e.printStackTrace();
}
while (resultSet.next()) {
ids = resultSet.getInt("id");
list.add(new EntryData(ids, resultSet.getDouble("phone_no"),
resultSet.getString("name"), resultSet.getString("lastname"), resultSet.getString("email_id"),
resultSet.getString("Address")));
}
TableID.getItems().addAll(list);
resultSet.close();
}
#FXML
void OnMenuFilter(ActionEvent event) {
LabelFilter.setText("Filter");
TextFiledFilter.setScaleX(1);
TextFiledFilter.setScaleY(1);
}
#FXML
void OnactionTextField(ActionEvent event) {
}
#FXML
void keyRelesed(ActionEvent event) {
}
}
FXML file
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.geometry.*?>
<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<BorderPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="716.0" prefWidth="1224.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.DataController">
<center>
<TableView fx:id="TableID" prefHeight="200.0" prefWidth="200.0" BorderPane.alignment="CENTER">
<columns>
<TableColumn fx:id="id" prefWidth="51.0" text="ID" />
<TableColumn fx:id="firstname" prefWidth="133.0" text="First Name" />
<TableColumn fx:id="lastname" prefWidth="106.0" text="Last Name" />
<TableColumn fx:id="emailid" prefWidth="121.0" text="Email-Id" />
<TableColumn fx:id="phoneno" prefWidth="75.0" text="Phone No" />
<TableColumn fx:id="address" prefWidth="233.0" text="Address" />
<TableColumn fx:id="Timee" minWidth="0.0" prefWidth="88.0" text="Time of entry" />
<TableColumn fx:id="Datee" minWidth="0.0" prefWidth="132.0" text="Date of Entry" />
</columns>
</TableView>
</center>
<left>
<VBox prefHeight="528.0" prefWidth="255.0" BorderPane.alignment="CENTER">
<children>
<TextField fx:id="Fname" promptText="First Name">
<VBox.margin>
<Insets bottom="40.0" left="5.0" right="5.0" top="5.0" />
</VBox.margin>
</TextField>
<TextField fx:id="Lname" promptText="Last Name">
<VBox.margin>
<Insets bottom="40.0" left="5.0" right="5.0" />
</VBox.margin>
</TextField>
<TextField fx:id="mailId" promptText="Email-Id">
<VBox.margin>
<Insets bottom="40.0" left="5.0" right="5.0" />
</VBox.margin>
</TextField>
<TextField fx:id="PhoneNo" promptText="Phone_No">
<VBox.margin>
<Insets bottom="40.0" left="5.0" right="5.0" />
</VBox.margin>
</TextField>
<TextArea fx:id="Address" prefHeight="200.0" prefWidth="200.0" promptText="Address">
<VBox.margin>
<Insets left="5.0" right="5.0" />
</VBox.margin>
</TextArea>
<Button fx:id="btnAdd" mnemonicParsing="false" onAction="#addBtnAction" text="Add">
<VBox.margin>
<Insets left="180.0" top="20.0" />
</VBox.margin>
</Button>
</children>
</VBox>
</left>
<top>
<MenuBar fx:id="MenuBar" BorderPane.alignment="CENTER">
<menus>
<Menu fx:id="menuFile" mnemonicParsing="false" text="File">
<items>
<MenuItem fx:id="MenuItemFilter" mnemonicParsing="false" onAction="#OnMenuFilter" text="Filter" />
<MenuItem mnemonicParsing="false" text="Close" />
</items>
</Menu>
<Menu mnemonicParsing="false" text="Edit">
<items>
<MenuItem mnemonicParsing="false" text="Delete" />
</items>
</Menu>
<Menu mnemonicParsing="false" text="Help">
<items>
<MenuItem mnemonicParsing="false" text="About" />
</items>
</Menu>
</menus>
</MenuBar>
</top>
<bottom>
<HBox BorderPane.alignment="CENTER">
<children>
<Label fx:id="LabelFilter" />
<TextField fx:id="TextFiledFilter" onAction="#OnactionTextField" onKeyReleased="#keyRelesed" scaleX="0.0" scaleY="0.0" />
</children>
<BorderPane.margin>
<Insets bottom="20.0" left="255.0" />
</BorderPane.margin>
</HBox>
</bottom>
</BorderPane>

passing parametres to FXML file from the controller

Hello I'm new to javaFX, and trying to create a simulation application of the scheduling algorithms.
I did the logic package, but still have problems with the UI. what i want to do is to allow the user to enter the number of jobs and in the next window i want to display text fields where he can put the executing time of each job, in other words i should display the text fields n time as the number of jobs given by the user.
this is what i did for the first interface :
<?xml version="1.0" encoding="UTF-8"?>
<GridPane xmlns:fx="http://javafx.com/fxml/1" alignment="center" hgap="10" styleClass="mainFxmlClass" vgap="10" fx:controller="ui.FXMLController">
<padding><Insets bottom="10" left="25" right="25" top="25" /></padding>
<stylesheets>
<URL value="#fxml.css" />
</stylesheets>
<children>
<Text id="welcome-text" text="Welcome" GridPane.columnIndex="0" GridPane.columnSpan="2" GridPane.rowIndex="0" />
<Label text="Le nombre de Processus:" GridPane.columnIndex="0" GridPane.rowIndex="1" />
<TextField fx:id="textField" GridPane.columnIndex="1" GridPane.rowIndex="1" />
<Label text="Choisissez un Algorithm d'Ordonancement :" GridPane.columnIndex="0" GridPane.rowIndex="2" />
<HBox alignment="bottom_right" spacing="10" GridPane.columnIndex="1" GridPane.rowIndex="5" />
<Text fx:id="actiontarget" GridPane.columnIndex="1" GridPane.rowIndex="7" />
<Button onAction="#handleButtonAction" text="Next" GridPane.columnIndex="1" GridPane.rowIndex="4" />
<MenuButton mnemonicParsing="false" prefHeight="25.0" prefWidth="150.0" text="Algo ... " GridPane.columnIndex="1" GridPane.rowIndex="2">
<items>
<MenuItem mnemonicParsing="true" text="Fifo" onAction="#handleButtonAction" />
<MenuItem mnemonicParsing="false" text="Tourniquet" />
<MenuItem mnemonicParsing="false" text="PCTER" />
<MenuItem mnemonicParsing="false" text="PCTE" />
</items>
</MenuButton>
</children>
</GridPane>
this is my controller :
public class FXMLController implements Initializable {
#FXML
private Label label;
#FXML
private Button button;
#FXML
private TextField textField;
#FXML
private Integer i;
#FXML
public void handleButtonAction() throws IOException{
String t = textField.getText();
IntegerStringConverter a = new IntegerStringConverter();
this.i = a.fromString(t);
Parent window = FXMLLoader.load(getClass().getResource("FXML1.fxml"));
Scene secondScene = new Scene(window);
Stage stage = new Stage();
stage.setScene(secondScene);
stage.show();
stage.show();
}
}
i dont know if there is a way to pass parameters from the controller to the FXML file and to do a loop in the FXML.. please help
If I understand you correctly, you want to request user input and create nodes in the GUI according to the input.
You can't create loops respectively control structures in a fxml file, but you can dynamically add and remove nodes (i.e. TextFields) by
defining a Vertical Box / Horizontal Box,
<VBox id="HBox" fx:id="myVBox" ...>
get the input as an integer,
int sum = Integer.parseInt(textField.getText());
and add the nodes in a for-loop,
for(int i=0, i<sum, i++) {
myVBox.getChildren().add(new TextField("executing time"));
}
and update the view.
Hope it helps.
AFAIK, you can't do that. You have to reverse the controL flow:
The controller should create the necessary controls (labels, textfields etc.) in a loop, possibly using a different FXML, which just defines that part.

Categories