Hello when I show the records with the button mostrar, all the records show, but when I am adding a new record with the button agregar the record doesn't show with that button, what I am doing wrong?. The method is good, but it seems that the last record is not visualized in the tableview this is my code, Please help.
The class
package application;
import javafx.collections.*;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ResourceBundle;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.MouseEvent;
public class Mostraregistros implements Initializable {
ObservableList <cliente> data =FXCollections.observableArrayList();
#FXML TableView<cliente> tablacliente;
#FXML TableColumn<cliente, String> nombrescol;
#FXML TableColumn<cliente,String > apellidoscol;
#FXML TableColumn<cliente, Integer> clienteid;
#FXML private Button mtn;
#Override
public void initialize(URL arg0, ResourceBundle arg1) {
mtn.setOnMouseClicked(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
Alert alert = new Alert(AlertType.INFORMATION);
alert.setTitle("Informacion");
alert.setHeaderText(null);
alert.setContentText("Mostrando Todos los Registros");
alert.showAndWait();
nombrescol.setCellValueFactory(new PropertyValueFactory <cliente, String>("nombres"));
apellidoscol.setCellValueFactory(new PropertyValueFactory <cliente, String>("apellidos"));
clienteid.setCellValueFactory(new PropertyValueFactory <cliente, Integer>("id_cliente"));
tablacliente.setItems(data);
}
});
Connection conn=null;{
try {
conn = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=prueba", "sa", "milkas87");
Statement mostrar=conn.createStatement();
ResultSet rs;
rs= mostrar.executeQuery("select * from cliente");
while ( rs.next() )
{
data.add(new cliente(
rs.getString("nombre"),
rs.getString("apellido"),
rs.getInt("id")
));
}
if(conn!=null)
System.out.println("conexion exitosa");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
fxml code
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.cell.*?>
<?import application.cliente.*?>
<?import application.Mostraregistros.*?>
<?import javafx.scene.text.*?>
<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.layout.AnchorPane?>
<AnchorPane prefHeight="634.0" prefWidth="626.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.ConexionSQL">
<children>
<Pane layoutX="5.0" layoutY="1.0" prefHeight="581.0" prefWidth="977.0">
<children>
<TextField fx:id="nm" layoutX="125.0" layoutY="70.0" prefHeight="32.0" prefWidth="205.0" text="nombres" />
<TextField fx:id="ap" layoutX="125.0" layoutY="133.0" prefHeight="32.0" prefWidth="205.0" text="apellidos" />
<Label layoutX="27.0" layoutY="70.0" prefHeight="32.0" prefWidth="137.0" text="NOMBRES" />
<Button fx:id="btn" layoutX="21.0" layoutY="216.0" mnemonicParsing="false" onAction="#btn" prefHeight="43.0" prefWidth="84.0" text="AGREGAR" />
<Label layoutX="27.0" layoutY="141.0" text="APELLIDOS" />
<TableView fx:id="tablacliente" layoutX="346.0" layoutY="47.0" prefHeight="448.0" prefWidth="553.0">
<columns>
<TableColumn fx:id="clienteid" prefWidth="225.0" text="CLIENTE ID"/>
<TableColumn fx:id="nombrescol" prefWidth="206.0" text="NOMBRES"/>
<TableColumn fx:id="apellidoscol" prefWidth="161.0" text="APELLIDOS"/>
</columns>
</TableView>
<Button fx:id="mtn" layoutX="138.0" layoutY="216.0" mnemonicParsing="false" prefHeight="43.0" prefWidth="144.0" text="MOSTRAR REGISTROS" />
</children>
</Pane>
</children>
</AnchorPane>
this is the agregar button code and the insert code
package application;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.input.MouseEvent;
public class ConexionSQL extends Mostraregistros{
#FXML private TextField nm;
#FXML private TextField ap;
#FXML private Button btn;
#FXML
private void btn(ActionEvent event) {
btn.setOnMouseClicked(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
Alert alert = new Alert(AlertType.INFORMATION);
alert.setTitle("Informacion");
alert.setHeaderText(null);
alert.setContentText("Registro Insertado Exitosamente");
alert.showAndWait();
}
});
Connection conn=null;
try {
conn = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=prueba", "sa", "milkas87");
Statement insertar=conn.createStatement();
insertar.executeUpdate("insert into cliente (nombre, apellido) values ('"+nm.getText()+"', '"+ap.getText()+"')");
if(conn!=null)
System.out.println("conexion exitosa");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
this is the cliente class
package application;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
public class cliente{
private StringProperty nombres;
private StringProperty apellidos;
private IntegerProperty id_cliente;
public cliente ( String nombres, String apellidos, Integer id_cliente) {
this.nombres= new SimpleStringProperty (nombres);
this.apellidos= new SimpleStringProperty ( apellidos);
this.id_cliente=new SimpleIntegerProperty (id_cliente);
}
public String getNombres() {
return nombres.get();
}
public void setNombres(String nombres) {
this.nombres=new SimpleStringProperty (nombres);
}
public String getApellidos() {
return apellidos.get();
}
public void setApellidos(String apellidos) {
this.apellidos=new SimpleStringProperty ( apellidos);
}
public Integer getId_cliente() {
return id_cliente.get();
}
public void setid_cliente(Integer id_cliente) {
this.id_cliente=new SimpleIntegerProperty (id_cliente);
}
}
Related
I'm trying to get a TableView TextFieldTableCell to be both wrapping the text and adjusting the cell height and also be editable at the same time.
So i'm able to make it wrapped or editable, but not at the same time.
I have been following this Thread and trying about a 100 different permutations and possibilities. I'm sure it is possible, but i'm reaching full fustration quickly. So any help would be highly appreciated!
I'm using SceneBuilder and importing the handles. MainFX.fxml: -->
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.TableColumn?>
<?import javafx.scene.control.TableView?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.StackPane?>
<StackPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8.0.171" xmlns:fx="http://javafx.com/fxml/1" fx:controller="wrappingEditableCellProject.Controller">
<children>
<AnchorPane prefHeight="200.0" prefWidth="200.0">
<children>
<TableView fx:id="tableView" prefHeight="200.0" prefWidth="200.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
<columns>
<TableColumn fx:id="id" prefWidth="75.0" text="id" />
<TableColumn fx:id="name" prefWidth="75.0" text="name" />
</columns>
</TableView>
</children>
</AnchorPane>
</children>
</StackPane>
My Main class:
package wrappingEditableCellProject;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class Main extends Application {
public static void main (String[] args) {
// TODO Auto-generated method stub
launch(args);
}
#Override
public void start(Stage primaryStage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("MainFX.fxml"));
primaryStage.setTitle("mainFx");
primaryStage.setScene(new Scene(root, 900, 600));
primaryStage.show();
}
}
My data entry class:
package wrappingEditableCellProject;
public class TableEntry {
private int id;
private String name;
public TableEntry (int id, String name){
this.id=id;
this.name=name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
My Controller class:
package wrappingEditableCellProject;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.collections.transformation.SortedList;
import javafx.fxml.FXML;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.util.converter.IntegerStringConverter;
public class Controller {
#FXML TableView<TableEntry> tableView;
#FXML TableColumn<TableEntry, Integer> id;
#FXML TableColumn<TableEntry, String> name;
private ObservableList<TableEntry> dataList = FXCollections.observableArrayList();
#SuppressWarnings({ "rawtypes", "unchecked" })
public void initialize(){
// Set editable
tableView.setEditable(true);
// Configure columns
id.setCellValueFactory(new PropertyValueFactory<>("id"));
id.setCellFactory(TextFieldTableCell.<TableEntry, Integer>forTableColumn(new IntegerStringConverter()));
id.setStyle("-fx-alignment: CENTER-LEFT;");
id.setEditable(false);
id.setSortable(false);
name.setCellValueFactory(new PropertyValueFactory<>("name"));
name.setCellFactory(WrappingTextFieldTableCell.<TableEntry>forTableColumn());
name.setStyle("-fx-alignment: CENTER-LEFT;");
name.setSortable(false);
name.setOnEditCommit(evt -> {
System.out.println("Edit comitted");
evt.getRowValue().setName(evt.getNewValue());
});
TableColumn[] tableColumns = {id,name};
tableView.getColumns().clear();
tableView.getColumns().addAll(tableColumns);
// add data to the table
dataList.clear();
dataList.add(new TableEntry(1, "Steve Upperton Stevenson"));
dataList.add(new TableEntry(2, "Peter May Parker"));
dataList.add(new TableEntry(3, "Tony Stark the machinist"));
dataList.add(new TableEntry(4, "Pepper Pots the CEO of Stark industies"));
FilteredList<TableEntry> dataFiltered = new FilteredList<>(dataList, b -> true);
SortedList<TableEntry> dataSorted = new SortedList<>(dataFiltered);
dataSorted.comparatorProperty().bind(tableView.comparatorProperty());
tableView.setItems(dataSorted);
}
}
Here is my custom cell class WrappingTextFieldTableCell:
package wrappingEditableCellProject;
import javafx.scene.control.Control;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.scene.text.Text;
import javafx.util.converter.DefaultStringConverter;
public class WrappingTextFieldTableCell<S> extends TextFieldTableCell<S, String> {
private final Text cellText;
public WrappingTextFieldTableCell() {
super(new DefaultStringConverter());
setPrefHeight(Control.USE_COMPUTED_SIZE);
this.cellText = createText();
}
#Override
public void cancelEdit() {
super.cancelEdit();
setGraphic(cellText);
}
#Override
public void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (!isEmpty() && !isEditing()) {
setGraphic(cellText);
}
}
private Text createText() {
Text text = new Text();
text.wrappingWidthProperty().bind(widthProperty());
text.textProperty().bind(itemProperty());
return text;
}
}
This solution allows me to edit the cell(I know there are easier ways for this), but the wrapping is not taking.
As mentioned i have tried 100 different ways to approach this challenge, but i think this would be the easiest to relate to for any assistance.
Thanks for any support!
I want to add a custom component (SwitchButton) to a column in a JavaFX TableView. I've looked at some examples with buttons and I'm just not understanding so far how to do it. Below is my practice table code along with the SwitchButton code I want to be able to put in the Active/Inactive column. The value for the SwitchButton (Active or Inactive) will be read from the database and when the user switches it, I'll want to trigger an action to write it to the database.
TableWithSwitchButtonView.fxml:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.TableColumn?>
<?import javafx.scene.control.TableView?>
<?import javafx.scene.layout.AnchorPane?>
<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="248.0" prefWidth="271.0" xmlns="http://javafx.com/javafx/8.0.171" xmlns:fx="http://javafx.com/fxml/1" fx:controller="tabletest.TableWithSwitchButtonController">
<children>
<TableView fx:id="configTableView" prefHeight="240.0" prefWidth="271.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
<columns>
<TableColumn fx:id="configColumn" prefWidth="138.0" text="Configuration Name" />
<TableColumn fx:id="activeColumn" prefWidth="131.0" text="Active/Inactive" />
</columns>
</TableView>
</children>
</AnchorPane>
TableWithSwitchButtonController.java:
package tabletest;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
public class TableWithSwitchButtonController implements Initializable
{
#FXML
private TableColumn<Config, String> configColumn;
#FXML
private TableColumn<Config, String> activeColumn;
#FXML
private TableView<Config> configTableView;
#Override
public void initialize(URL url, ResourceBundle rb)
{
// Add Cell Value Factory
configColumn.setCellValueFactory(new PropertyValueFactory<Config,
String>("configName"));
activeColumn.setCellValueFactory(new PropertyValueFactory<Config,
String>("configActive"));
// populate the Column lists (this will be coming from the database)
ObservableList<Config> configList =
FXCollections.<Config>observableArrayList(
new Config("Config 1", "active"),
new Config("Config 2", "active"),
new Config("Config 3", "inactive")
);
configTableView.getItems().addAll(configList);
}
public class Config
{
private String configName;
private String configActive;
public Config(String name, String active)
{
configName = name;
configActive = active;
}
public String getConfigName()
{
return configName;
}
public void setConfigName(String name)
{
configName = name;
}
public String getConfigActive()
{
return configActive;
}
public void setConfigActive(String active)
{
configActive = active;
}
};
}
TableTest.java:
package tabletest;
import java.io.IOException;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class TableTest extends Application
{
#Override
public void start(Stage primaryStage)
{
try
{
FXMLLoader loader = new FXMLLoader(getClass().getResource("TableWithSwitchButtonView.fxml"));
Scene scene = new Scene((Parent) loader.load());
primaryStage.setScene(scene);
primaryStage.setTitle("Table Test");
primaryStage.show();
}
catch (IOException ignored)
{
}
}
public static void main(String[] args)
{
launch(args);
}
}
SwitchButton.java:
package tabletest;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.Button;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.Label;
public class SwitchButton extends Label
{
private SimpleBooleanProperty switchedOn = new SimpleBooleanProperty(true);
public SwitchButton()
{
Button switchBtn = new Button();
switchBtn.setPrefWidth(40);
switchBtn.setOnAction(new EventHandler<ActionEvent>()
{
#Override
public void handle(ActionEvent t)
{
switchedOn.set(!switchedOn.get());
}
});
setGraphic(switchBtn);
switchedOn.addListener(new ChangeListener<Boolean>()
{
#Override
public void changed(ObservableValue<? extends Boolean> ov,
Boolean t, Boolean t1)
{
if (t1)
{
setText("ACTIVE");
setStyle("-fx-background-color: green;-fx-text-fill:white;");
setContentDisplay(ContentDisplay.RIGHT);
}
else
{
setText("INACTIVE");
setStyle("-fx-background-color: grey;-fx-text-fill:black;");
setContentDisplay(ContentDisplay.LEFT);
}
}
});
switchedOn.set(false);
}
public SimpleBooleanProperty switchOnProperty() { return switchedOn; }
}
I have a very strange problem with my test application. I need to fill the JavaFX TableView element with some data. Here is the code:
fxmldocumentController.java
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;
import javafx.scene.control.TableView; //A
import javafx.scene.control.TableColumn; //B
import javafx.scene.control.cell.PropertyValueFactory; //C
public class fxmldocumentController implements Initializable
{
#FXML
private TableView<employees> mainTableView;
#FXML
private TableColumn<employees, Integer> age;
#FXML
private TableColumn<employees, String> userName, companyName;
#Override
public void initialize(URL url, ResourceBundle rb)
{
// TODO:
mainTableView.getItems().
add(new employees("Yuri P. Bodrov", "VMware", 35));
mainTableView.getItems().
add(new employees("Ivan Y. Bodrov", "VMware", 5));
mainTableView.getItems().
add(new employees("Peter Y. Bodrov", "VMware", 2));
// A problem starts here:
age.setCellValueFactory(new PropertyValueFactory<>("age"));
userName.setCellValueFactory(new PropertyValueFactory<>("userName"));
companyName.
setCellValueFactory(new PropertyValueFactory<>("companyName"));
}
}
fxmldocument.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" prefHeight="300.0" prefWidth="400.0" style="-fx-
background-color: white;"
xmlns="http://javafx.com/javafx/8"
xmlns:fx="http://javafx.com/fxml/1"
fx:controller="sampletableviewapp00.fxmldocumentController">
<children>
<Label fx:id="testLabel" layoutX="14.0" layoutY="14.0" style="-fx-
background-color: white;" text="Employees. TableView." textFill="#505050">
<font>
<Font size="14.0" />
</font>
</Label>
<TableView fx:id="mainTableView" layoutX="12.0" layoutY="50.0"
prefHeight="200.0" prefWidth="377.0">
<columns>
<TableColumn prefWidth="90.0" text="UserName" />
<TableColumn prefWidth="119.0" text="CompanyName" />
<TableColumn prefWidth="84.0" text="Age" />
</columns>
</TableView>
</children>
</AnchorPane>
Sampletableviewapp00.java
package sampletableviewapp00;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class Sampletableviewapp00 extends Application
{
#Override
public void start(Stage stage) throws Exception
{
Parent root = FXMLLoader.load(getClass().
getClassLoader().getResource("fxmldocument.fxml"));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args)
{
launch(args);
}
}
employees.java
package sampletableviewapp00;
public class employees
{
String userName, companyName;
int age;
// Generate Properties. Getters:
public int GetAge()
{
return age;
}
public String GetUserName()
{
return userName;
}
public String GetCompanyName()
{
return companyName;
}
// Generate Properties. Setters:
public void SetAge(int age)
{
this.age = age;
}
public void SetUserName(String userName)
{
this.userName = userName;
}
public void SetCompanyName(String companyName)
{
this.companyName = companyName;
}
// Generate Constructor of Employees class:
public employees(String userName, String companyName, int age)
{
this.userName = userName;
this.companyName = companyName;
this.age = age;
}
}
When I run this application the NetBeans IDE 8.2 returns this stack of exceptions/errors: see outputError.png as attachment
outputError.png
outputError02.PNG
Dear colleagues! Do you have any ideas to resolve this problem? Could you try to write this code by yourself and run? Thanks in advance! :-)
You have fxmldocument.xml but tried to load "fxmldocument.fxml".
Rename the file to have fxml extension.
Also make sure you put the fxml file under /resources/yourpackagepath/ folder and load as:
Sampletableviewapp00.class.getResource("fxmldocument.fxml")
This line is triggering the exception:
Parent root = FXMLLoader.load(getClass().
getClassLoader().getResource("fxmldocument.fxml"));
Your fxml document's extension is xml in your project and you are trying to load it as .fxml in the above line.
Rename fxmldocument.xml to fxmldocument.fxml.
i am trying to transform my previous javafx program into an MVC machine. i actually do not have any compilation error neither do i have runtime errors. but when i run my login application i cannot see the database values in the combobox.
yes of course i can login, it works fine.
This are my codes for the combobox splited into LoginView, LoginController, and LoginModel:
package com.login;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.control.ComboBox;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Created by DELL PC on 7/25/2016.
*/
public class LoginModel {
Connection connection;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
public LoginModel()
{
connection = SqliteConnection.connector();
if(connection == null)
{
System.exit(1);
}
}
public boolean isDBConnected()
{
try {
return !connection.isClosed();
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
public ComboBox fillCombobox()
{
try
{
final ObservableList options = FXCollections.observableArrayList();
String query = "SELECT role from admin";
preparedStatement = connection.prepareStatement(query);
resultSet = preparedStatement.executeQuery();
while(resultSet.next())
{
options.add(resultSet.getString("role"));
}
preparedStatement.close();
resultSet.close();
}
catch(SQLException ex)
{
Logger.getLogger(LoginModel.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
public boolean isLogin(String user, String pass) throws SQLException
{
String query = "SELECT * FROM admin WHERE username = ? and password = ?";
try {
preparedStatement = connection.prepareStatement(query);
preparedStatement.setString(1, user);
preparedStatement.setString(2, pass);
resultSet = preparedStatement.executeQuery();
if(resultSet.next())
{
return true;
}
else
{
return false;
}
}catch(Exception e){
return false;
}
finally
{
preparedStatement.close();
resultSet.close();
}
}
}
code for Controller
package com.login;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
import java.io.IOException;
import java.net.URL;
import java.sql.SQLException;
import java.util.ResourceBundle;
public class LoginController implements Initializable{
public LoginModel loginModel = new LoginModel();
#FXML
private TextField txtusername;
#FXML
private PasswordField pwpaswword;
#FXML
private Label isConnected;
#FXML
private ComboBox comboBox;
#Override
public void initialize(URL location, ResourceBundle resources) {
comboBox.getItems().contains(loginModel.fillCombobox());
if(loginModel.isDBConnected())
{
isConnected.setText("Connected");
}
else
{
isConnected.setText("Not Connected");
}
}
public void Login(ActionEvent event)
{
try {
if (loginModel.isLogin(txtusername.getText(), pwpaswword.getText()))
{
isConnected.setText("Login Successfully ");
((Node)event.getSource()).getScene().getWindow().hide();
Stage window = new Stage();
FXMLLoader loader = new FXMLLoader();
Pane root = loader.load(getClass().getResource("CivilStateView.fxml").openStream());
CivilStateController civilStateController = (CivilStateController)loader.getController();
civilStateController.getUser(txtusername.getText());
Scene scene = new Scene(root);
window.setTitle("Hello World");
window.setScene(scene);
window.show();
}
else
{
isConnected.setText("Login Unsuccessful");
}
} catch (SQLException e) {
isConnected.setText("Exception occurred:" + e);
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
the view is made with fxml:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.geometry.*?>
<?import javafx.scene.text.*?>
<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<?import javafx.geometry.Insets?>
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="346.0" prefWidth="360.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.login.LoginController">
<children>
<Label fx:id="isConnected" layoutX="31.0" layoutY="30.0" prefHeight="36.0" prefWidth="150.0" text="Status" textFill="#f20f0f">
<font>
<Font size="18.0" />
</font>
</Label>
<TextField fx:id="txtusername" layoutX="26.0" layoutY="75.0" prefHeight="48.0" prefWidth="160.0" promptText="Username">
<font>
<Font size="19.0" />
</font>
</TextField>
<PasswordField fx:id="pwpaswword" layoutX="26.0" layoutY="137.0" prefHeight="48.0" prefWidth="160.0" promptText="Password">
<font>
<Font size="19.0" />
</font>
</PasswordField>
<ComboBox fx:id="comboBox" layoutX="26.0" layoutY="196.0" prefHeight="36.0" prefWidth="150.0">
<padding>
<Insets left="20.0" />
</padding>
</ComboBox>
<Button layoutX="26.0" layoutY="245.0" mnemonicParsing="false" onAction="#Login" prefHeight="36.0" prefWidth="68.0" text="Button" />
</children>
</AnchorPane>
I was able to create a test case that runs this though not using any of the DB interaction. The critical parts are:
public class LoginModel {
...
public ObservableList fillCombobox() {
ObservableList options = FXCollections.observableArrayList();
// replace this with your DB code to add the options.
for (int i = 1; i < 10; i++) {
options.add("Role " + i);
}
//
return options;
}
}
public class LoginController implements Initializable {
...
#Override
public void initialize(URL location, ResourceBundle resources) {
comboBox.setItems(loginModel.fillCombobox());
...
}
}
I keep on searching for an answer but still I can't find the right way to do it (or probably the mistakes in my codes). I am using javafx with scenebuilder. mySQL is the database that I am using. help please :(
package cedproject;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import java.sql.*;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Group;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
/**
* FXML Controller class
*
* #author My Lightstream
*/
public class FXMLController implements Initializable {
public java.sql.PreparedStatement ps;
public java.sql.ResultSet rs;
#FXML
private AnchorPane donationWindow;
//#FXML
//private TableView<?> tblView;
#FXML
TableView<userdata> tblView= new TableView<>();
#FXML
private TableColumn<?, ?> colOR;
#FXML
private TableColumn<?, ?> colAmount;
#FXML
private Button btnNew;
#FXML
private TextField txtSearch;
private static java.sql.Connection con;
private static Statement stat;
private PreparedStatement prep;
private ObservableList<userdata> data;
#FXML
private Button btnLoad;
#FXML
private Group gp;
// </userdata>
/**
#FXML
private Button btnNew;
#FXML
private AnchorPane donationWindow;
/**
* Initializes the controller class.
*/
#Override
public void initialize(URL url, ResourceBundle rb) {
try{
ps = new Connect().connectDatabase();
ps.execute();
tblView.getItems().setAll(this.data);
}catch(Exception e){
}
lagay();
}
public void lagay(){
try{
String query = "select * from receipt";
tblView.getItems().clear();
ps = con.prepareStatement("select * from receipt");
rs = ps.executeQuery(query);
}catch(Exception e){
System.out.println("mali ka shunga");
}
ObservableList<userdata> data = FXCollections.observableArrayList();
try{
while(rs.next()){
data.add(new userdata(
rs.getInt("ORNUM"),
rs.getInt("AMOUNT")
));}
}catch(Exception e){}
}
public void tableView()throws Exception{
tblView.getItems().clear();
rs = ps.executeQuery("SELECT ORNUM,AMOUNT FROM RECEIPT");
ObservableList<userdata> data = FXCollections.observableArrayList();
TableColumn column1 = new TableColumn("ORNUM");
column1.setCellValueFactory(new javafx.scene.control.cell.PropertyValueFactory<>("ornum"));
TableColumn column2 = new TableColumn("Amount");
column2.setCellValueFactory(new javafx.scene.control.cell.PropertyValueFactory<>("amount"));
tblView.getColumns().addAll(column1,column2);
tblView.getChildrenUnmodifiable();
}
#FXML
public void handleButtonAction2(ActionEvent event) {
}
#FXML
public void activated(MouseEvent event) {
}
private void onClicked(ActionEvent event) throws SQLException {
/* tblView.getItems().clear();
rs = ps.executeQuery("SELECT ORNUM,AMOUNT FROM RECEIPT");
ObservableList<userdata> data = FXCollections.observableArrayList();
TableColumn column1 = new TableColumn("ORNUM");
column1.setCellValueFactory(new PropertyValueFactory<>("ORNUM"));
TableColumn column2 = new TableColumn("Amount");
column2.setCellValueFactory(new PropertyValueFactory<>("Amount"));
tblView.getColumns().addAll(column1,column2);*/
ObservableList<userdata> data = FXCollections.observableArrayList();
try{ String query = "select * from receipt";
tblView.getItems().clear();
ps = con.prepareStatement(query);
rs = ps.executeQuery("SELECT * from receipt");
while(rs.next()){
tblView.getItems().add(new userdata(
rs.getInt("ORNUM"),
rs.getInt("AMOUNT")
));
tblView.setItems(data);
}
ps.close();
rs.close();
}catch(Exception e){
}
}
#FXML
private void onClicked(MouseEvent event) throws Exception {
System.out.println("gawin mo");
ObservableList<userdata> data = FXCollections.observableArrayList();
System.out.println("ginawa");
tableView();
try{
String query = "select * from receipt";
tblView.getItems().clear();
ps = new Connect().connectDatabase();
ps = new Connect().connectDatabase();
rs = ps.executeQuery(query);
while(rs.next()){
tblView.getItems().add(new userdata(
rs.getInt("ORNUM"),
rs.getInt("AMOUNT")
));
tblView.setItems(data);
}
}catch(Exception e){
System.out.print("asdqweasd");
}
}
/**
*
* #param event
*/
/* #FXML
public void konekplis(SortEvent<C> event) {
}*/
}
package cedproject;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
/**
*enter code here
* #author My Lightstream
*/
public class userdata {
public SimpleIntegerProperty Ornum;
public SimpleIntegerProperty Amount;
public userdata(Integer ornum, Integer amount) {
this.Ornum = new SimpleIntegerProperty(ornum);
this.Amount = new SimpleIntegerProperty(amount);
}
userdata(String string) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
userdata(String string, String string0, String string1, String string2, String string3, String string4) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
public Integer getOrnum() {
return Ornum.get();
}
public Integer getAmount() {
return Amount.get();
}
public void setOrnum(Integer ornum) {
this.Ornum.set(ornum);
}
public void setAmount(Integer amount) {
this.Amount.set(amount);
}
}
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.effect.*?>
<?import java.lang.*?>
<?import java.net.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<AnchorPane id="AnchorPane" fx:id="donationWindow" onDragDetected="#activated" prefHeight="482.0" prefWidth="696.0" styleClass="mainFxmlClass" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="cedproject.FXMLController">
<stylesheets>
<URL value="#fxml.css" />
</stylesheets>
<children>
<AnchorPane layoutY="8.0" prefHeight="482.0" prefWidth="696.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
<children>
<TableView fx:id="tblView" layoutX="21.0" layoutY="87.0" prefHeight="181.0" prefWidth="655.0">
<columns>
<TableColumn fx:id="colOR" prefWidth="326.0" text="OR Number" />
<TableColumn fx:id="colAmount" prefWidth="325.0" text="Amount" />
</columns>
</TableView>
<Button fx:id="btnNew" layoutX="500.0" layoutY="35.0" mnemonicParsing="false" onAction="#handleButtonAction2" prefHeight="25.0" prefWidth="78.0" text="NEW" />
<Button layoutX="587.0" layoutY="35.0" mnemonicParsing="false" prefHeight="25.0" prefWidth="78.0" text="EDIT" />
<TextField fx:id="txtSearch" layoutX="40.0" layoutY="35.0" prefHeight="25.0" prefWidth="204.0" promptText="Search" />
<TextArea editable="false" layoutX="19.0" layoutY="336.0" prefHeight="132.0" prefWidth="655.0">
<effect>
<DropShadow height="14.0" radius="6.5" width="14.0" />
</effect>
</TextArea>
<Label layoutX="26.0" layoutY="305.0" prefHeight="17.0" prefWidth="68.0" text="Description:" />
<Button fx:id="btnLoad" layoutX="424.0" layoutY="35.0" mnemonicParsing="false" onMouseClicked="#onClicked" prefHeight="25.0" prefWidth="68.0" text="Load" />
<Group fx:id="gp" />
</children>
<cursor>
<Cursor fx:constant="DEFAULT" />
</cursor>
</AnchorPane>
</children>
</AnchorPane>
Please help :(