Digital clock doesn't update - javafx

I'm trying to integrate a Digital Clock in a label, in a FXML controller, but it doesnt work, it doesnt'update, only show the original text of the label ( dunno )
Fxml:
<?import javafx.scene.control.ChoiceBox?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.RadioButton?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.AnchorPane?>
<AnchorPane id="AnchorPane" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="320.0" prefWidth="480.0" style="-fx-background-color: SteelBlue;" xmlns="http://javafx.com/javafx/8.0.65" xmlns:fx="http://javafx.com/fxml/1" fx:controller="simulazione.esame.ControllerPannello">
<children>
<Label fx:id="orario" layoutX="32.0" layoutY="65.0" prefHeight="25.0" prefWidth="247.0" text="dunno" />
<ChoiceBox fx:id="settimana" layoutX="14.0" layoutY="116.0" prefWidth="150.0" />
<Label layoutX="195.0" layoutY="108.0" text="Stato Impianto" />
<RadioButton fx:id="onRadio" layoutX="207.0" layoutY="129.0" mnemonicParsing="false" text="on" />
<RadioButton fx:id="offRadio" layoutX="263.0" layoutY="129.0" mnemonicParsing="false" text="off" />
<AnchorPane layoutX="181.0" layoutY="180.0" prefHeight="135.0" prefWidth="289.0">
<children>
<Label layoutX="14.0" layoutY="23.0" text="Temp per raffreddamento" />
<Label layoutX="14.0" layoutY="74.0" text="Temp per riscaldamento" />
<TextField layoutX="176.0" layoutY="19.0" prefHeight="25.0" prefWidth="79.0" />
<TextField layoutX="176.0" layoutY="70.0" prefHeight="25.0" prefWidth="79.0" />
</children>
</AnchorPane>
</children>
</AnchorPane>
Fxml controller:
import java.net.URL;
import java.util.Calendar;
import java.util.ResourceBundle;
import javafx.animation.Animation;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.geometry.Insets;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.Label;
import javafx.scene.control.RadioButton;
import javafx.scene.control.ToggleGroup;
import javafx.util.Duration;
/**
*
* #author Antonio
*/
public class ControllerPannello implements Initializable {
#FXML
private ChoiceBox settimana;
#FXML
private Label orario, boh;
#FXML
private RadioButton onRadio, offRadio;
private ObservableList<String> sett =
FXCollections.<String>observableArrayList("Lunedì", "Martedì", "Mercoledì",
"Giovedì", "Venerdì", "Sabato", "Domenica");
ToggleGroup stato = new ToggleGroup();
#FXML
private void handleButtonAction(ActionEvent event) {
}
#Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
onRadio.setToggleGroup(stato);
offRadio.setToggleGroup(stato);
settimana.setItems(sett);
orario = new DigitalClock();
}
}
DigitalClock.java
import java.io.IOException;
import java.net.URL;
import javafx.animation.*;
import javafx.event.*;
import javafx.scene.control.Label;
import javafx.util.Duration;
import java.util.Calendar;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.stage.Stage;
class DigitalClock extends Label {
public DigitalClock() {
bindToTime();
}
// the digital clock updates once a second.
public void bindToTime() {
Timeline timeline = new Timeline(
new KeyFrame(Duration.seconds(0),
new EventHandler<ActionEvent>() {
#Override public void handle(ActionEvent actionEvent) {
Calendar time = Calendar.getInstance();
String hourString = StringUtilities.pad(2, ' ', time.get(Calendar.HOUR) == 0 ? "12" : time.get(Calendar.HOUR) + "");
String minuteString = StringUtilities.pad(2, '0', time.get(Calendar.MINUTE) + "");
String secondString = StringUtilities.pad(2, '0', time.get(Calendar.SECOND) + "");
String ampmString = time.get(Calendar.AM_PM) == Calendar.AM ? "AM" : "PM";
setText(hourString + ":" + minuteString + ":" + secondString + " " + ampmString);
}
}
),
new KeyFrame(Duration.seconds(1))
);
timeline.setCycleCount(Animation.INDEFINITE);
timeline.play();
}
}
class StringUtilities {
/**
* Creates a string left padded to the specified width with the supplied padding character.
* #param fieldWidth the length of the resultant padded string.
* #param padChar a character to use for padding the string.
* #param s the string to be padded.
* #return the padded string.
*/
public static String pad(int fieldWidth, char padChar, String s) {
StringBuilder sb = new StringBuilder();
for (int i = s.length(); i < fieldWidth; i++) {
sb.append(padChar);
}
sb.append(s);
return sb.toString();
}
}

Related

How to refresh/update the tableview in a tab controller from another tab controller JavaFx

I developed a simple demo JavaFx app with Sqlite since command line(terminal) with two tabs (tab1-Info and tab2-Register), in tab1-Info there is a tableview "myTable" that shows only id, name and lastname and in tab2-Register shows the textfields to register name and lastname as seen in the following figures.
In the archives i use tab1.fxml and tab2.fxml which tab1 calls Controller.java and tab2.fxml calls Tab2Controller.java.
Actually the simple demo JavaFx app with Sqlite is working perfectly, but i do not know how to refresh tableview "myTable" when i pressed the button "save" which is in another controller tab2.fxml (Tab2Controller.java) different from where tab1-info TableView "myTable" is located.
I wish that when i pressed the button "save", automatically "myTable" updates/refresh the new content data, any advice in order to solve this issue?
Here are the java program archives.
principal.java
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class principal extends Application {
public static void main(String[] args) {
Application.launch(principal.class, args);
}
#Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("scheme.fxml"));
stage.setTitle("Demo tab version");
stage.setScene(new Scene(root, 300, 400));
stage.show();
}
}
scheme.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import java.net.*?>
<?import javafx.geometry.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.text.*?>
<GridPane xmlns:fx="http://javafx.com/fxml" hgap="20" vgap="20" styleClass="root" gridLinesVisible="false">
<padding><Insets top="25" right="2" bottom="20" left="2" /></padding>
<Text id="welcome-text" text="Demo tab" GridPane.columnIndex="0" GridPane.rowIndex="0" GridPane.columnSpan="6" GridPane.rowSpan="1"/>
<TabPane fx:id="tabPane" xmlns:fx="http://javafx.com/fxml" prefHeight="500.0" prefWidth="300.0" GridPane.columnIndex="0" GridPane.rowIndex="1" GridPane.columnSpan="6" tabClosingPolicy="UNAVAILABLE">
<tabs>
<Tab fx:id="tab1" text="Info" >
<fx:include source="Tab1.fxml"/>
</Tab>
<Tab fx:id="tab2" text="Register" >
<fx:include source="Tab2.fxml"/>
</Tab>
</tabs>
</TabPane>
<stylesheets>
<URL value="#Login.css" />
</stylesheets>
Tab1.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import java.net.*?>
<?import javafx.geometry.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.text.*?>
<?import javafx.scene.control.TabPane?>
<?import javafx.scene.control.Tab?>
<?import javafx.scene.control.ComboBox?>
<?import javafx.scene.control.cell.*?>
<GridPane fx:controller="Controller" xmlns:fx="http://javafx.com/fxml" hgap="20" vgap="20" >
<!-- <ScrollPane visible="true" GridPane.columnIndex="0" GridPane.rowIndex="0" GridPane.columnSpan="1" GridPane.rowSpan="5"> -->
<VBox layoutX="15.0" layoutY="76.0" prefHeight="528.0" prefWidth="1200.0">
<children>
<TableView fx:id="myTable" prefHeight="512.0" prefWidth="500.0" />
</children>
</VBox>
</GridPane>
Tab2.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import java.net.*?>
<?import javafx.geometry.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.text.*?>
<?import javafx.scene.control.TabPane?>
<?import javafx.scene.control.Tab?>
<?import javafx.scene.control.Label?>
<GridPane xmlns:fx="http://javafx.com/fxml" fx:controller="Tab2Controller" hgap="10" vgap="5">
<Text id="informacion" text="Personal Information" GridPane.columnIndex="1" GridPane.rowIndex="0" style="-fx-fill:white" />
<Text text="Name" GridPane.columnIndex="1" GridPane.rowIndex="2" style="-fx-fill:white"/>
<TextField fx:id="name" GridPane.columnIndex="1" GridPane.rowIndex="3" prefWidth="150.0"/>
<Text text="Lastname" GridPane.columnIndex="1" GridPane.rowIndex="4" style="-fx-fill:white" />
<TextField fx:id="lastname" GridPane.columnIndex="1" GridPane.rowIndex="5" prefWidth="300.0" />
<Button text="Save" GridPane.columnIndex="1" GridPane.rowIndex="7" prefHeight="20" prefWidth="90" GridPane.halignment="RIGHT" onAction="#handleSubmitButtonAction"/>
</GridPane>
Controller.java
import java.sql.*;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
public class Controller implements Initializable{
#FXML
public TableView myTable;
#Override
public void initialize(URL url, ResourceBundle rb) {
TableColumn<Integer, Person> column1 = new TableColumn<>("Id");
column1.setCellValueFactory(new PropertyValueFactory<>("id"));
TableColumn<String, Person> column2 = new TableColumn<>("Name");
column2.setCellValueFactory(new PropertyValueFactory<>("nomCom"));
TableColumn<String, Person> column3 = new TableColumn<>("LastName");
column3.setCellValueFactory(new PropertyValueFactory<>("ApellPatern"));
myTable.getColumns().add(column1);
myTable.getColumns().add(column2);
myTable.getColumns().add(column3);
String sql = "SELECT id, nomCom, ApellPatern FROM warehouses";
try (Connection conn = this.connect();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql)){
System.out.println("Opened database successfully");
while (rs.next()) {
System.out.println(rs.getInt("id")+ "\t" + rs.getString("nomCom") + "\t" + rs.getString("ApellPatern"));
myTable.getItems().add(new Person(rs.getInt("id"),rs.getString("nomCom"),rs.getString("ApellPatern")));
}/*Aqui finaliza el while */
/*Aqui finaliza el executequery*/
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}/* End of initialize */
public class Person {
private Integer id=null;
private String nomCom=null;
private String ApellPatern=null;
public Person(Integer id, String nomCom, String ApellPatern){
this.id=id;
this.nomCom=nomCom;
this.ApellPatern=ApellPatern;
}
public Integer getId(){
return id;
}
public String getNomCom() {
return nomCom;
}
public String getApellPatern(){
return ApellPatern;
}
}
private Connection connect() {
String url ="jdbc:sqlite:test.db";
Connection conn = null;
try {
conn = DriverManager.getConnection(url);
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return conn;
}
}
Tab2Controller.java
import java.sql.*;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import java.sql.SQLException;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Alert;
public class Tab2Controller implements Initializable{
/*#FXML private fx:id="name" */
#FXML private TextField name;
/*#FXML private fx:id="lastname" ;*/
#FXML private TextField lastname;
#Override
public void initialize(URL url, ResourceBundle rb) {
/* No information*/
}
#FXML protected void handleSubmitButtonAction(ActionEvent event) {
String nomCom=name.getText();
String ApellPatern=lastname.getText();
String sql = "INSERT INTO warehouses(nomCom,ApellPatern) VALUES(?,?)";
try (Connection conn = this.connect();
PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setString(1,nomCom);
pstmt.setString(2, ApellPatern);
pstmt.executeUpdate();
} catch (SQLException e) {
System.out.println(e.getMessage());
}
Alert alert = new Alert(AlertType.INFORMATION);
alert.setTitle("Information Dialog");
alert.setHeaderText(null);
alert.setContentText("The information has been saved succesfully");
alert.showAndWait();
}
private Connection connect() {
// SQLite connection string
// String url = "jdbc:sqlite:C://sqlite/db/test.db";
String url ="jdbc:sqlite:test.db";
Connection conn = null;
try {
conn = DriverManager.getConnection(url);
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return conn;
}
}
Any help is appreciated. Thank you in advance

JAVAFX ComboBox does not display value names correctly [duplicate]

This question already has an answer here:
How do I add a value to items in a ComboBox in JavaFX
(1 answer)
Closed 4 years ago.
Hi I am trying to populate data from a database into a Combo Box, but when I click on the dropdown menu, it does not list the names of the items correctly. I can't figure out why.
Here is what appears when I click on the combobox image
Any help is appreciated thanks!
Edit:I tried using a String Converter but it still does not display the output . Did I use the String Converter correctly?
OrderController class
package sample;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.fxml.FXML;
import javafx.scene.control.TableColumn;
import javafx.event.ActionEvent;
import javafx.scene.control.ComboBox;
import javafx.stage.Stage;
import java.io.IOException;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ResourceBundle;
public class Ordercontroller implements Initializable {
#FXML ComboBox<Orderitems> itemdropdown;
#FXML ComboBox<String> droppax;
#FXML ComboBox<String> tablenum;
#FXML
ObservableList<Orderitems> choice = FXCollections.observableArrayList();
ObservableList<String> pax =
FXCollections.observableArrayList("1","2","3","4","5","6","7");
ObservableList<String> tableno =
FXCollections.observableArrayList("1","2","3","4","5","6","7");
#Override
public void initialize(URL location, ResourceBundle resources) {
itemdrop();
}
public void itemdrop(){
itemdropdown.setValue(null);
itemdropdown.setItems(choice);
droppax.setItems(pax);
tablenum.setItems(tableno);
try {
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
String path = "C:\\Users\\franc\\Desktop\\Database\\CSIA1.accdb";
String url = "jdbc:ucanaccess://" + path;
Connection conn = DriverManager.getConnection(url);
Statement st = conn.createStatement();
String sql = "Select * from Menu";
ResultSet rs = st.executeQuery(sql);
while (rs.next()) {
choice.add(new Orderitems(rs.getString("Item")));
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
Orderitems class
package sample;
import java.awt.*;
import javafx.util.StringConverter;
public class Orderitems extends Ordercontroller{
String Item;
Ordercontroller order = new Ordercontroller();
public Orderitems(String item) {
this.Item = item;
}
public String getItem() {
return Item;
}
public void setItem(String item) {
Item = item;
}
public void start() throws Exception{
itemdropdown.setConverter(new StringConverter<Orderitems>() {
#Override
public String toString(Orderitems object) {
return null;
}
#Override
public Orderitems fromString(String string) {
return null;
}
});}}
Order FXML file
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.ComboBox?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.TableColumn?>
<?import javafx.scene.control.TableView?>
<?import javafx.scene.control.TextArea?>
<?import javafx.scene.layout.AnchorPane?>
<AnchorPane prefHeight="400.0" prefWidth="600.0"
xmlns="http://javafx.com/javafx/8.0.172-ea"
xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.Ordercontroller">
<children>
<TableView fx:id="Ordertable" layoutX="204.0" layoutY="51.0"
prefHeight="200.0" prefWidth="345.0">
<columns>
<TableColumn fx:id="Oitem" prefWidth="75.0" text="Item" />
<TableColumn fx:id="Oprice" prefWidth="75.0" text="Price" />
<TableColumn fx:id="Ospecial" prefWidth="155.0" text="Special
Requests" />
</columns>
</TableView>
<Button layoutX="475.0" layoutY="266.0" mnemonicParsing="false" text="Add
Item" />
<Label layoutX="38.0" layoutY="238.0" text="Table Number" />
<TextArea fx:id="specialreq" layoutX="278.0" layoutY="352.0"
prefHeight="65.0" prefWidth="200.0" text="Special Requests" />
<Button layoutX="82.0" layoutY="312.0" mnemonicParsing="false" text="Load" />
<Label layoutX="68.0" layoutY="68.0" text="No. of Pax" />
<Button layoutX="496.0" layoutY="369.0" mnemonicParsing="false" text="Add"
/>
<Button layoutX="473.0" layoutY="308.0" mnemonicParsing="false"
text="Delete Item" />
<ComboBox fx:id="itemdropdown" layoutX="308.0" layoutY="270.0"
onAction="#itemdrop" prefWidth="150.0" />
<ComboBox fx:id="tablenum" layoutX="34.0" layoutY="270.0"
prefWidth="150.0" />
<ComboBox fx:id="droppax" layoutX="34.0" layoutY="96.0" prefWidth="150.0"
/>
<Button layoutX="28.0" layoutY="14.0" mnemonicParsing="false"
onAction="#returnhome" text="Exit" />
</children>
</AnchorPane>
Try implementing toString on your OrderItem class.
#Override
public String toString() {
return item;
}

How to show last record in tableview?

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);
}
}

Javafx cannot update the text for tempDisplay label

I cannot set the text for the tempDisplay label by using settext() in connectArduino method. It only can show part of the string, like the symbol "°C", just like the screen shot shows. But the string "input" can be print out actually.
Here is my controller class
import javafx.application.Platform;
import javafx.scene.chart.LineChart;
import javafx.scene.control.*;
import javafx.event.ActionEvent;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.ComboBox;
import javafx.scene.control.ToggleButton;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.stage.Stage;
import jssc.SerialPort;
import static jssc.SerialPort.MASK_RXCHAR;
import jssc.SerialPortEvent;
import jssc.SerialPortException;
import jssc.SerialPortList;
public class MainController {
SerialPort arduinoPort = null;
ObservableList<String> portList;
public String input;
public static double max;
public static double min;
public static String phoneNumber;
public static final String ACCOUNT_SID =
"AC935209d3c44660b4a550e3380249857a";
public static final String AUTH_TOKEN = "42bcd28e23344404c737eb3499d2a747";
final int NUM_OF_POINT = 300;
XYChart.Series series;
#FXML
private ComboBox comboBox;
#FXML
private ToggleButton modeButton;
#FXML
private ToggleButton ledButton;
#FXML
private Button connectButton;
#FXML
private TextArea displayArea;
#FXML
private Label tempDisplay;
#FXML
private NumberAxis xAxis;
#FXML
private NumberAxis yAxis;
#FXML
private LineChart lineChart;
#FXML
private void initialize(){
displayArea.setEditable(false);
detectPort();
comboBox.setPromptText("Port List");
comboBox.setItems(portList);
setLineChart();
//sendSMS();
}
private void detectPort(){
portList = FXCollections.observableArrayList();
String[] serialPortNames = SerialPortList.getPortNames();
portList.addAll(serialPortNames);
}
private void connect(){
disconnectArduino();
if(connectButton.getText().equals("Connect")) {
connectArduino(comboBox.getValue().toString());
}
ledButton.setSelected(false);
}
public boolean connectArduino(String port){
displayArea.appendText("connect Arduino");
if(port.isEmpty()){
alert("Connect Failed!");
return false;
}
else {
connectButton.setText("Disconnect");
boolean success = false;
SerialPort serialPort = new SerialPort(port);
try {
serialPort.openPort();
serialPort.setParams(
SerialPort.BAUDRATE_9600,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
serialPort.setEventsMask(MASK_RXCHAR);
serialPort.addEventListener((SerialPortEvent serialPortEvent) -> {
if (serialPortEvent.isRXCHAR()) {
try {
input = serialPort.readString(serialPortEvent
.getEventValue());
System.out.println(input);
if (input.contains("false")) {
alert("Unplugged Sensor");
} else {
Platform.runLater(() -> {
String st = input + " °C";
tempDisplay.setText(st);
// shiftSeriesData(Float.parseFloat(input));
});
}
} catch (SerialPortException ex) {
Logger.getLogger(MainController.class.getName())
.log(Level.SEVERE, null, ex);
alert("No Data Available");
}
}
});
arduinoPort = serialPort;
success = true;
} catch (SerialPortException ex) {
Logger.getLogger(MainController.class.getName())
.log(Level.SEVERE, null, ex);
System.out.println("SerialPortException: " + ex.toString());
alert("No Data Available");
}
return success;
}
}
Here is my fxml class
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.chart.LineChart?>
<?import javafx.scene.chart.NumberAxis?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.ComboBox?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.TextArea?>
<?import javafx.scene.control.ToggleButton?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.text.Font?>
<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="627.0" prefWidth="664.0" xmlns="http://javafx.com/javafx/8.0.111" xmlns:fx="http://javafx.com/fxml/1" fx:controller="MainController">
<children>
<LineChart fx:id="lineChart" createSymbols="false" layoutY="74.0" prefHeight="343.0" prefWidth="396.0" title="Temperature of Session">
<xAxis>
<NumberAxis autoRanging="false" label="Time (s)" side="BOTTOM" tickUnit="100" fx:id="xAxis" upperBound="300"/>
</xAxis>
<yAxis>
<NumberAxis fx:id="yAxis" autoRanging="false" label="Temperature (°C)" lowerBound="10" side="RIGHT" upperBound="50" />
</yAxis>
</LineChart>
<TextArea fx:id="displayArea" editable="false" layoutX="15.0" layoutY="426.0" prefHeight="186.0" prefWidth="635.0" />
<Label layoutX="94.0" layoutY="14.0" prefHeight="60.0" prefWidth="482.0" text="Team Placeholder Themometer Interface">
<font>
<Font size="24.0" />
</font>
</Label>
<Button fx:id="connectButton" layoutX="475.0" layoutY="145.0" mnemonicParsing="false" onAction="#connectPressed" prefHeight="80.0" prefWidth="131.0" text="Connect">
<font>
<Font size="18.0" />
</font>
</Button>
<Button fx:id="setButton" layoutX="475.0" layoutY="241.0" mnemonicParsing="false" onAction="#setPressed" prefHeight="34.0" prefWidth="131.0" text="Set SMS" />
<Label layoutX="400.0" layoutY="314.0" prefHeight="27.0" prefWidth="131.0" text="Current Temperature" />
<ComboBox fx:id="comboBox" layoutX="475.0" layoutY="94.0" prefHeight="34.0" prefWidth="131.0" />
<ToggleButton fx:id="ledButton" layoutX="540.0" layoutY="360.0" mnemonicParsing="false" onAction="#ledPressed" prefHeight="34.0" prefWidth="109.0" text="Show on LEDs" />
<ToggleButton fx:id="modeButton" layoutX="540.0" layoutY="314.0" mnemonicParsing="false" onAction="#modePressed" prefHeight="34.0" prefWidth="109.0" text="In Fahrenheit" />
<Label fx:id="tempDisplay" layoutX="400.0" layoutY="341.0" prefHeight="39.0" prefWidth="131.0" textFill="#e10707">
<font>
<Font size="32.0" />
</font>
</Label>
</children>
Screen shot for the interface

Java FX onAction

When working on this project I am having issues figuring out how to get the Buttons in the second window to fire an onAction. I can get the first window to open the second window however i can't seem to figure out how to then have the buttons in the second window use an onAction
Code for second window:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.text.Text?>
<AnchorPane id="AnchorPane" fx:id="createPersonAnchor" prefHeight="247.0" prefWidth="285.0" xmlns="http://javafx.com/javafx/8.0.111" xmlns:fx="http://javafx.com/fxml/1" >
<children>
<Button layoutX="171.0" layoutY="180.0" mnemonicParsing="false" onAction="#cancelCreatePersonAction" prefHeight="37.0" prefWidth="79.0" text="Cancel" />
<TextField layoutX="115.0" layoutY="28.0" />
<TextField layoutX="115.0" layoutY="78.0" />
<Button layoutX="47.0" layoutY="180.0" mnemonicParsing="false" onAction="#createPersonAction" prefHeight="37.0" prefWidth="79.0" text="Create" />
<Text layoutX="29.0" layoutY="45.0" strokeType="OUTSIDE" strokeWidth="0.0" text="First Name:" wrappingWidth="69.677734375" />
<Text layoutX="29.0" layoutY="95.0" strokeType="OUTSIDE" strokeWidth="0.0" text="Last Name:" wrappingWidth="69.677734375" />
</children>
</AnchorPane>
Controller Code:
package project1;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.layout.AnchorPane;
/**
* FXML Controller class
*
* #author Fomnus
*/
public class FXMLCreatePersonController implements Initializable {
/**
* Initializes the controller class.
*/
public FXMLCreatePersonController(){
FXMLLoader loader = new FXMLLoader(getClass().getResource("FXMLCreatePerson.fxml"));
loader.setController(this);
try{
loader.load();
}catch(Exception e){
System.out.println(e.getMessage()+ "FXMLCreatePersonController failed");
}
}
#FXML AnchorPane createPersonAnchor;
#FXML public void setFXMLCreatePersonAnchorPane(AnchorPane fxmlCreatePerson){
createPersonAnchor = fxmlCreatePerson;
}
#FXML public AnchorPane getFXMLCreatePersonAnchorPane(){
return createPersonAnchor;
}
#Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
}
}
Main Controller Code:
package project1;
import java.awt.Desktop.Action;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.StackPane;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
/**
*
* #author fomnus
*/
public class FXMLDashboardController implements Initializable {
#Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
}
#FXML
private void createPersonWindow(ActionEvent event) {
FXMLCreatePersonController createpersoncntrl = new FXMLCreatePersonController();
AnchorPane fxmlCreatePersonAnchorPane = createpersoncntrl.getFXMLCreatePersonAnchorPane();
StackPane fxmlCreatePersonstackpane = new StackPane();
fxmlCreatePersonstackpane.getChildren().add(fxmlCreatePersonAnchorPane);
Scene fxmlCreatePersonscene = new Scene(fxmlCreatePersonstackpane);
Stage fxmlCreatePersonstage = new Stage();
fxmlCreatePersonstage.setScene(fxmlCreatePersonscene);
fxmlCreatePersonstage.show();
}
}

Resources