Getting database data to TableView - java

I get an error highlight with this code at:
ResultSet rs = stmt.executeQuery(sql);
'executeQuery' gets "red error highlight" in netbeans
How do I get it to work properly and get the application to work and populate the JavaFx TableView with data from the database.
Here's the rest of the Code:
The Controller Class:
import java.beans.Statement;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.LinkedList;
import java.util.List;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
public class TesterUIController implements Initializable {
static String JDBC_DRIVER = "org.h2.Driver";
static String DB_URL = "jdbc:h2:file:C:/MyBeautifulCherrishabledb";
static final String USER = "sa";
static final String PASS = "";
public static Connection conn = null;
#FXML
private TableView<dataClass> Table;
#FXML
private Button TestButton;
#FXML
private TableColumn<dataClass, Integer> colKey;
#FXML
private TableColumn<dataClass, String> colSalesNo;
public static void main(String[] args) {
System.out.println("Main has run");
}
#Override
public void initialize(URL fxmlFileLocation, ResourceBundle resources) {
TestButton.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
System.out.println("Button Pressed");
colKey.setCellValueFactory(new PropertyValueFactory<dataClass, Integer>("Key"));
colSalesNo.setCellValueFactory(new PropertyValueFactory<dataClass, String>("SalesNo"));
Table.getItems().setAll(gobbledyGook());
}
});
}
public class dataClass {
private IntegerProperty Key;
public void setKey(int value) {
KeyProperty().set(value);
}
public int getKey() {
return KeyProperty().get();
}
public IntegerProperty KeyProperty() {
if (Key == null) {
Key = new SimpleIntegerProperty(this, "Key");
}
return Key;
}
private StringProperty SalesNo;
public void setSalesNo(String value) {
SalesNoProperty().set(value);
}
public String getSalesNo() {
return SalesNoProperty().get();
}
public StringProperty SalesNoProperty() {
if (SalesNo == null) {
SalesNo = new SimpleStringProperty(this, "SalesNo");
}
return SalesNo;
}
}
private List<dataClass> gobbledyGook() {
Statement stmt = null;
List ll = new LinkedList();
try {
// STEP 2: Register JDBC driver
Class.forName(JDBC_DRIVER);
// STEP 3: Open a connection
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Connected database successfully...");
// STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = (Statement) conn.createStatement();
String sql = "SELECT id, LovelyGuy FROM LOVELYPEOPLE";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
int Key = rs.getInt(1);
double saleNo = rs.getDouble(2);
NumberFormat formatter = new DecimalFormat("###########");
String SalesNo = formatter.format(saleNo);
System.out.println(Key + ", " + SalesNo); //key + ", " + saleNo);
dataClass roww = new dataClass();
roww.setKey(Key);
roww.setSalesNo(SalesNo);
ll.add(roww);
}
} catch (ClassNotFoundException | SQLException ex) {
Logger.getLogger(TesterUIController.class.getName()).log(Level.SEVERE, null, ex);
}
return ll;
}
}
The main Class
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class TesterUI extends Application {
#Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("TesterUI.fxml"));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
The FXML:
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<AnchorPane id="AnchorPane" prefHeight="600.0" prefWidth="700.0" xmlns:fx="http://javafx.com/fxml" fx:controller="testerui.TesterUIController">
<children>
<Button fx:id="TestButton" layoutX="14.0" layoutY="14.0" mnemonicParsing="false" text="Button" />
<Pane layoutY="35.0" prefHeight="565.0" prefWidth="700.0">
<children>
<TableView fx:id="Table" layoutX="14.0" layoutY="14.0" prefHeight="226.0" prefWidth="672.0">
<columns>
<TableColumn prefWidth="75.0" text="Column X" fx:id="colKey" />
<TableColumn prefWidth="75.0" text="Column X" fx:id="colSalesNo" />
</columns>
</TableView>
</children>
</Pane>
</children>
</AnchorPane>
Update:
The ErrorStackTrace:
ResultSet rs = stmt.executeQuery(sql);
symbol: method executeQuery(String)
location: variable stmt of type Statement
Note: C:\Users\Revilo\Downloads\GitHub\Tables\Tablas-JavaFX--FXML--master\src\TesterUI\src\testerui\TesterUIController.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
1 error

you have imported
import java.beans.Statement;
You should use
import java.sql.Statement;

Related

Sharing screen via Java socket programming

I am trying to send the live screen of the client to the server. It's a one-way communication till now. They seem to connect, but somehow the whole data might not be sent. I can't understand where the problem lies. Only a still image is shared in spite of a continuous stream of images. Will I have to use another AnimationTimer in the server-class and how? If not, how can I achieve a live sharing of the screen? My code is as follows:
Image info class shared by both server & client:
package sample;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.image.Image;
import javafx.scene.image.WritableImage;
import javax.imageio.ImageIO;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class imageData implements Serializable {
private transient Image wi;
private String msg;
private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException {
s.defaultReadObject();
wi = SwingFXUtils.toFXImage(ImageIO.read(s), null);
}
private void writeObject(ObjectOutputStream s) throws IOException {
s.defaultWriteObject();
ImageIO.write(SwingFXUtils.fromFXImage(wi, null), "png", s);
}
public void setWi(WritableImage wi) { this.wi = wi; }
public Image getWi() { return wi; }
}
Server main class:
package sample;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.image.WritableImage;
import javafx.stage.Stage;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Main extends Application {
#Override
public void start(Stage primaryStage) throws Exception{
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("sample.fxml"));
Parent root = loader.load();
primaryStage.setTitle("Hello World");
primaryStage.setScene(new Scene(root));
primaryStage.show();
Controller controller = loader.getController();
controller.setM(this);
try{
ServerSocket ss = new ServerSocket(8888);
Socket s = ss.accept();
new conn(s, controller);
}catch(Exception e){
System.out.println(e);
}
}
public void setIV(WritableImage wi) { }
public static void main(String[] args) {
launch(args);
}
}
Server conn class:
package sample;
import javafx.scene.control.Control;
import javafx.scene.image.WritableImage;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class conn {
private Socket s;
private ObjectInputStream is;
private Main m;
private Controller controller;
public conn(Socket s, Controller controller) throws Exception {
this.s = s;
ObjectInputStream is = new ObjectInputStream(s.getInputStream());
this.controller = controller;
connTh cth = new connTh(s, is, controller);
cth.start();
}
public void setMain(Main m) { this.m = m; }
public void setController(Controller controller) { this.controller = controller; }
public class connTh extends Thread{
Socket s;
private ObjectInputStream is;
private Controller controller;
public connTh(Socket s, ObjectInputStream is, Controller controller) throws Exception{
this.s = s;
this.is = is;
this.controller = controller;
}
#Override
public void run(){
while(true){
try{
imageData id = (imageData)is.readObject();
Image newImage = id.getWi();
controller.setIv(newImage);
//WritableImage oldImage = (WritableImage) controller.getIv();
}catch(Exception e){
System.out.println(e);
}
}
}
}
}
Server controller:
package sample;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.image.WritableImage;
import java.awt.*;
public class Controller {
private Main m;
private conn c;
#FXML private ImageView iv;
#FXML private Label lbl;
public void setIv(Image wi) { iv.setImage(wi); }
public Image getIv() { return iv.getImage(); }
public void setM(Main m) { this.m = m; }
public void setC(conn c) { this.c = c; }
}
Server fxml:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.Separator?>
<?import javafx.scene.image.ImageView?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.ColumnConstraints?>
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.layout.RowConstraints?>
<GridPane alignment="center" hgap="10" vgap="10" xmlns:fx="http://javafx.com/fxml" xmlns="http://javafx.com/javafx" fx:controller="sample.Controller">
<columnConstraints>
<ColumnConstraints />
</columnConstraints>
<rowConstraints>
<RowConstraints />
</rowConstraints>
<children>
<AnchorPane prefHeight="500.0" prefWidth="500.0">
<children>
<ImageView fx:id="iv" fitHeight="347.0" fitWidth="436.0" layoutX="32.0" layoutY="47.0" pickOnBounds="true" preserveRatio="true" />
<Label fx:id="lbl" layoutX="189.0" layoutY="7.0" prefHeight="30.0" prefWidth="72.0" text="VIEW" />
<Separator layoutX="113.0" layoutY="35.0" prefWidth="200.0" />
</children>
</AnchorPane>
</children>
</GridPane>
Client main class:
package sample;
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.embed.swing.SwingFXUtils;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Pos;
import javafx.geometry.Rectangle2D;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.image.WritableImage;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.robot.Robot;
import javafx.scene.text.Text;
import javafx.scene.text.TextAlignment;
import javafx.stage.Screen;
import javafx.stage.Stage;
import javax.imageio.ImageIO;
import javax.swing.text.Position;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;
public class Main extends Application {
#Override
public void start(Stage primaryStage) throws Exception{
Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
primaryStage.setTitle("Hello World");
ImageView iv = new ImageView();
iv.setFitWidth(500);
iv.setFitHeight(400);
Text t = new Text("Screen Sharing");
t.setTextAlignment(TextAlignment.CENTER);
t.setFill(Color.FIREBRICK);
t.setStyle("-fx-font: 18 arial;");
Button b = new Button("Exit");
b.setAlignment(Pos.BASELINE_CENTER);
b.setOnAction(event -> {
Platform.exit();
});
VBox v = new VBox(10);
v.getChildren().addAll(t,iv,b);
primaryStage.setScene(new Scene(v, 500, 500));
primaryStage.show();
try{
Socket s = new Socket("localhost", 8888);
ObjectOutputStream os = new ObjectOutputStream(s.getOutputStream());
new network(s, os);
}catch(Exception e){
System.out.println(e);
}
}
public static void main(String[] args) {
launch(args);
}
}
Client network class:
package sample;
import javafx.animation.AnimationTimer;
import javafx.geometry.Rectangle2D;
import javafx.scene.image.WritableImage;
import javafx.scene.robot.Robot;
import javafx.stage.Screen;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Timer;
import java.util.TimerTask;
public class network {
private Socket s;
private ObjectOutputStream os;
public network(Socket s, ObjectOutputStream os){
this.s = s;
this.os = os;
new AnimationTimer() {
int c = 1;
final Robot robot = new Robot();
final Rectangle2D bounds = Screen.getPrimary().getBounds();
WritableImage i =robot.getScreenCapture(wi,bounds);
imageData id = new imageData();
#Override
public void handle(long now) {
if(c == 1){
try{
c++;
id.setWi(i);
os.writeObject(id);
os.reset();
}catch(Exception e){
System.out.println(e);
}
}
else{
try{
WritableImage oldImage = (WritableImage)id.getWi();
WritableImage newImage = robot.getScreenCapture(oldImage,bounds);
if(oldImage != newImage){
id.setWi(newImage);
os.writeObject(id);
os.reset();
}
}catch(Exception e){
System.out.println(e);
}
}
}
}.start();
}

Adding Parameters to calling a class prevents it's opening of new window method from working. Java FX

When passing parameters through the calling of a new class from the controller, it seems that the existence of parameters prevents the class from carrying out it's method of opening a new window correctly (a method that exists within the called class that opens a new window). However, when re-creating example data within the class within the initialize method and not passing through the parameters, calling the class and its new window creation method works okay.
The building of a table/graphs methods etc are called within the initialise method of the new class. The creation of a new window is a method that is called within the controller after the class itself has been initialised.
Any help would be appreciated. Thanks.
Main:
package sample;
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 {
#Override
public void start(Stage primaryStage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
primaryStage.setTitle("Example"); //set the name of the title
primaryStage.setScene(new Scene(root, 1200, 750)); //width and height of pane
primaryStage.sizeToScene();
primaryStage.show();
primaryStage.setMinWidth(primaryStage.getWidth());
primaryStage.setMinHeight(primaryStage.getHeight());
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Controller:package sample;
import java.util.ArrayList;
import java.util.Random;
import java.util.Set;
public class Controller {
public Controller() {
}
public void openWin() {
// Example Data Set
ArrayList<ArrayList<Double>> data = new ArrayList<>();
for (double j = 0; j < 5; j++) {
ArrayList<Double> exampleDataSet = new ArrayList<>();
exampleDataSet.add(j);
for (int i = 0; i < 5; i++) {
Random r = new Random();
double randomValue = 0 + (100 - 0) * r.nextDouble();
exampleDataSet.add(randomValue);
}
data.add(exampleDataSet);
}
//Example Headers for Data Set
String headers = "Header1, Header2, Header3, Header4, Header5";
//Open New Window (this is upon button click)
Win newWin = new Win(headers, data);
newWin.openNewWin();
}
//
//
}
Win Class:package sample;
import javafx.beans.property.ReadOnlyObjectWrapper;
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.TableColumn;
import javafx.scene.control.TableView;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import java.util.ArrayList;
import java.util.List;
public class Win {
#FXML private TableView<ObservableList<Double>> tableView = new TableView<>();
private Stage stage = new Stage();
String headers[] = null;
String items[] = null;
List<String> columns = new ArrayList<String>();
List<String> rows = new ArrayList<String>();
ObservableList<ObservableList<Double>> csvData = FXCollections.observableArrayList();
private String newHeaders;
private ArrayList<ArrayList<Double>> data = new ArrayList<>();
public Win(String headers, ArrayList data) {
this.newHeaders = headers;
this.data = data;
}
public void initialize() {
generateTable(newHeaders, data);
}
public void openNewWin() {
try {
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("win.fxml"));
Parent root1 = fxmlLoader.load();
stage.initStyle(StageStyle.DECORATED);
stage.initModality(Modality.APPLICATION_MODAL);
stage.setTitle("Table");
stage.setScene(new Scene(root1));
stage.show();
} catch(Exception e) {
System.out.println("Cannot load new window");
System.err.println(e.getMessage());
System.out.println(newHeaders);
System.out.println(data);
}
}
public void generateTable(String newHeaders, ArrayList<ArrayList<Double>> dataset) {
try {
System.out.println(newHeaders);
System.out.println(dataset);
headers = newHeaders.split(",");
for (String w : headers) {
columns.add(w);
}
for (int i = 0; i < columns.size(); i++) {
final int finalIdx = i;
TableColumn<ObservableList<Double>, Double> column = new TableColumn<>(columns.get(i));
column.setCellValueFactory(param -> new ReadOnlyObjectWrapper<>(param.getValue().get(finalIdx))); //Set text
tableView.getColumns().add(column);
}
for (ArrayList<Double> array : dataset) {
ObservableList<Double> row = FXCollections.observableArrayList();
row.clear();
for (double number : array) {
row.add(number);
}
csvData.add(row);
}
tableView.setItems(csvData);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Sample FXML:<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.geometry.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<GridPane id="gridPane" alignment="top_center" gridLinesVisible="false" hgap="10" vgap="10" xmlns="http://javafx.com/javafx/10.0.2-internal" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.Controller"> <!--will show gaps between columns, rows & cells-->
<!-- can use center -->
<!--forcing width of columns-->
<padding>
<Insets bottom="10" left="30" right="30" top="10" /> <!-- will have a gap between title and below-->
</padding>
<Button onAction="#openWin" GridPane.rowIndex="0" GridPane.columnIndex="10" text="Exit"/>
</GridPane>
win FXML:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<GridPane id="gridPane" alignment="top_center" gridLinesVisible="false" hgap="10" prefHeight="650.0" prefWidth="1000.0" vgap="10" xmlns="http://javafx.com/javafx/10.0.2-internal" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.Win">
<TableView fx:id="tableView" GridPane.columnIndex="0" GridPane.columnSpan="3" GridPane.rowIndex="3" />
</GridPane>
<!--The Grid Pane for win would include other items like buttons and graphs-->

How can I print out current CPU usage and update it in Java Scene Builder (FXML)

I'm trying to build a CPU monitor tool in scene builder (FXML) and I cannot get it to update the CPU usage in a FXML label. I can get it to print out the cpu usage in the start but that is it. Here is what I have so far.
java file
package cpumonitorfxml;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.util.Duration;
public class CPUMonitorFXML extends Application {
#Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));
FXMLDocumentController start = new FXMLDocumentController();
Timeline timeline = new Timeline(new KeyFrame(Duration.millis(100), (ActionEvent) -> {
double cpu = FXMLDocumentController.getCPUUsage();
System.out.println("CPU: " + cpu);
}));
timeline.setCycleCount(100);
timeline.play();
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
FXMLDocument
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.image.*?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<AnchorPane id="AnchorPane" prefHeight="301.0" prefWidth="206.0" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/8" fx:controller="cpumonitorfxml.FXMLDocumentController">
<children>
<Button fx:id="button" layoutX="34.0" layoutY="229.0" onAction="#handleButtonAction" prefHeight="25.0" prefWidth="69.0" text="Click Me!" />
<Label fx:id="label" layoutX="126" layoutY="120" minHeight="16" minWidth="69" />
<ImageView fitHeight="150.0" fitWidth="200.0" layoutX="28.0" layoutY="28.0" pickOnBounds="true" preserveRatio="true">
<image>
<Image url="#gauge.png" />
</image>
</ImageView>
</children>
</AnchorPane>
And FXMLDocumentController
package cpumonitorfxml;
import java.lang.management.ManagementFactory;
import java.lang.management.OperatingSystemMXBean;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.animation.Animation;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.util.Duration;
public class FXMLDocumentController implements Initializable {
private Timeline timeline;
private KeyFrame keyFrame;
private final double tickTimeInSeconds = 0.01;
private double secondsElapsed = 0.0;
private final double angleDeltaPerSeconds = 6.0;
#FXML
private Label label;
#FXML
private void handleButtonAction(ActionEvent event) {
System.out.println("You clicked me!");
label.setText("Hello World!");
}
public void FXMLDocumentController(){
timeline.play();
setupTimer();
}
public static double getCPUUsage() {
OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
double value = 0;
for (Method method : operatingSystemMXBean.getClass().getDeclaredMethods()) {
method.setAccessible(true);
if (method.getName().startsWith("getSystemCpuLoad")
&& Modifier.isPublic(method.getModifiers())) {
try {
value = (double) method.invoke(operatingSystemMXBean);
} catch (Exception e) {
value = 0;
}
return value;
}
}
return value;
}
public void setupTimer(){
if(isRunning()){
timeline.stop();
}
keyFrame = new KeyFrame(Duration.millis(tickTimeInSeconds * 1000),
(ActionEvent actionEvent) -> {
update();
});
timeline = new Timeline(keyFrame);
timeline.setCycleCount(Animation.INDEFINITE);
}
private void update(){
secondsElapsed += tickTimeInSeconds;
String str = Double.toString(getCPUUsage());
label.setText(str);
}
public boolean isRunning(){
if(timeline != null){
if(timeline.getStatus() == Animation.Status.RUNNING){
return true;
}
}
return false;
}
#Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
}
}
I know that this is pretty rough, I am pretty new to FXML. Obviously there is alot of work to be done, but my main hurdle to get over is creating a timeline(?) that will update the cpu usage as a label. I created a very similar program in JavaFX and had a much easier time with that.
I think you are creating confusion by trying to use the Main instead of the Controller to handle your code.
Main
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
/**
*
* #author Sedrick
*/
public class JavaFXApplication74 extends Application {
#Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
Controller
import java.lang.management.ManagementFactory;
import java.lang.management.OperatingSystemMXBean;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.util.Duration;
/**
*
* #author Sedrick
*/
public class FXMLDocumentController implements Initializable {
#FXML
private Label label;
Timeline timeline;
OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
#FXML
private void handleButtonAction(ActionEvent event) {
switch(timeline.getStatus())
{
case PAUSED:
case STOPPED:
timeline.play();
break;
case RUNNING:
timeline.pause();
break;
}
}
#Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
timeline = new Timeline(new KeyFrame(Duration.seconds(1), (ActionEvent event) -> {
label.setText(getCPUUsage().toString());
}));
timeline.setCycleCount(Timeline.INDEFINITE);
}
public Double getCPUUsage() {
double value = 0;
for (Method method : operatingSystemMXBean.getClass().getDeclaredMethods()) {
method.setAccessible(true);
if (method.getName().startsWith("getSystemCpuLoad")
&& Modifier.isPublic(method.getModifiers())) {
try {
return (double) method.invoke(operatingSystemMXBean);
} catch (Exception e) {
value = 0;
}
}
}
return value;
}
}
FXML
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<AnchorPane id="AnchorPane" prefHeight="200" prefWidth="320" xmlns:fx="http://javafx.com/fxml/1" fx:controller="javafxapplication74.FXMLDocumentController">
<children>
<Button layoutX="126" layoutY="90" text="Click Me!" onAction="#handleButtonAction" fx:id="button" />
<Label layoutX="126" layoutY="120" minHeight="16" minWidth="69" fx:id="label" />
</children>
</AnchorPane>

JavaFX, TableView - Is HashMap<personName, List<Events>> or HashMap<day, List<Events>> the solution to my problem

I'm at a crossroads right now. The problem I'm having is coloring in the cells of the TableView<Person>. I have 3 columns: firstName, lastName, and the Days Column (which is actually 60 columns representing the next 60 days from today). Each Person will have something to do on these days called "events" (1 event max per day, with a startDate and endDate). Each person can therefore have up to 60 events when I read them from an XML file. Here's a picture to illustrate what I am referring too.
Scheduler
This is the Person class
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import stack.Event;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
public class Person{
private StringProperty name;
private StringProperty last;
private String group;
private ArrayList<Event> events;
static ArrayList<String> strDays = new ArrayList<String>();
public ArrayList<Event> getEvents() {
return events;
}
public void setEvents(ArrayList<Event> events) {
this.events = new ArrayList<>(events);
}
public String getName() {
return name.get();
}
public void setName(String name) {
this.name.set(name);;
}
public StringProperty nameProperty(){
return name;
}
public String getLast() {
return last.get();
}
public void setLast(String last) {
this.last.set(last);
}
public StringProperty lastProperty(){
return last;
}
public String getGroups() {
return group;
}
public void setGroups(String group) {
this.group = group;
}
public Person(String name, String last, String group, ArrayList<Event> events){
this.name = new SimpleStringProperty(name);
this.last = new SimpleStringProperty(last);
this.group = group;
this.events = new ArrayList<Event>(events);
}
public static void print(){
Date current = new Date(); //current first date
SimpleDateFormat ft = new SimpleDateFormat("yyyy\n MM/dd\n E"); //format wanted
ArrayList<Date> dates = new ArrayList<Date>();
Calendar cal = Calendar.getInstance();
cal.setTime(current);
cal.add(Calendar.DATE, 60); //setting the tableView end date
Date startDate = current;
Date endDate = cal.getTime();
Calendar c1 = DateToCalendar(startDate);
Calendar c2 = DateToCalendar(endDate);
//this generates all the dates between the start date and end date
while (!areEqualDate(c1, c2)){
ft.format(c1.getTime());
dates.add(c1.getTime());
c1.add(Calendar.DAY_OF_YEAR,1);
}
//this formats the dates
for (int i = 0; i < dates.size(); i++){
strDays.add(i, ft.format(dates.get(i)));
}
}
private static boolean areEqualDate(Calendar c1, Calendar c2) {
if (c1.get(Calendar.YEAR) != c2.get(Calendar.YEAR))
return false;
if (c1.get(Calendar.MONTH) != c2.get(Calendar.MONTH))
return false;
if (c1.get(Calendar.DAY_OF_YEAR) != c2.get(Calendar.DAY_OF_YEAR))
return false;
return true;
}
private static Calendar DateToCalendar(Date startDate) {
Calendar cal = Calendar.getInstance();
cal.setTime(startDate);
return cal;
}
}
The Event class
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
public class Event {
private String event;
private String startDate;
private String endDate;
public String getStartDate() {
return startDate;
}
public void setStartDate(String startDate) {
this.startDate = startDate;
}
public String getEndDate() {
return endDate;
}
public void setEndDate(String endDate) {
this.endDate = endDate;
}
public Event(){
this.event= "";
this.startDate = "";
this.endDate = "";
}
public Event(String event, String startDate, String endDate){
this.event = event;
this.startDate = startDate;
this.endDate = endDate;
}
public String getEvent() {
return event;
}
public void setEvent(String event) {
this.event = event;
}
}
My sample.fxml class, package name of my project is stack
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.image.*?>
<?import java.net.*?>
<?import javafx.geometry.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.text.*?>
<?import javafx.scene.layout.VBox?>
<?import javafx.scene.text.Text?>
<?import javafx.scene.control.ChoiceBox?>
<?import java.lang.String?>
<?import javafx.collections.FXCollections?>
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.control.cell.*?>
<?import javafx.collections.*?>
<?import javafx.scene.control.MenuBar?>
<?import javafx.scene.control.SeparatorMenuItem?>
<?import javafx.scene.control.MenuItem?>
<?import javafx.scene.layout.Pane?>
<?import javafx.scene.control.ScrollBar?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.CheckBox?>
<BorderPane xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml"
fx:controller="stack.Controller" fx:id="container">
<center>
<GridPane alignment="CENTER">
<padding>
<Insets top="40" left="20" bottom="20" right="20"></Insets>
</padding>
<?language javascript?>
<Label fx:id="title" text="Scheduler" alignment="CENTER" GridPane.columnIndex="0" GridPane.rowIndex="0"></Label>
<TableView fx:id="table" GridPane.columnIndex="0" GridPane.rowIndex="2" GridPane.hgrow="ALWAYS" GridPane.vgrow="ALWAYS" editable="true">
<columnResizePolicy>
<TableView fx:constant="CONSTRAINED_RESIZE_POLICY" />
</columnResizePolicy>
<columns>
<TableColumn fx:id="firstColumn" text="First Name" minWidth="100" maxWidth="100">
<cellValueFactory>
<PropertyValueFactory property="name"/>
</cellValueFactory>
</TableColumn>
<TableColumn fx:id="secondColumn" text="Last Name" minWidth="100" maxWidth="120">
<cellValueFactory>
<PropertyValueFactory property="last" />
</cellValueFactory>
</TableColumn>
</columns>
</TableView>
<fx:script>
table.getSelectionModel().setCellSelectionEnabled(true);
table.getSelectionModel().setSelectionMode(javafx.scene.control.SelectionMode.MULTIPLE);
</fx:script>
</GridPane>
</center>
</BorderPane>
Main class
import javax.print.DocFlavor.URL;
import javafx.application.*;
import javafx.fxml.FXMLLoader;
import javafx.stage.Stage;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.MenuItem;
import javafx.scene.image.Image;
public class main extends Application {
public Scene theme;
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) throws Exception {
try {
Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
primaryStage.setTitle("Stack");
Scene scene = new Scene(root, 800, 650);
primaryStage.setScene(scene);
primaryStage.show();
} catch(Exception e) {
e.printStackTrace();
}
}
}
My code is wrong but I have an understanding why it's doing what it's doing. this is what I have currently in my
Controller class
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import javafx.application.Platform;
import javafx.beans.property.ReadOnlyStringWrapper;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TablePosition;
import javafx.scene.control.TableRow;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.util.Callback;
public class Controller implements Initializable {
public TableView<Person> table = new TableView<>();
public TableColumn<Person, String> firstColumn, secondColumn, days;
public TableColumn[] tablecols;
//public TableColumn<Person, Event> days;
int count = 0;
//TempTestClass test = new TempTestClass();
private String current = "";
ArrayList<String> dayArray = new ArrayList<String>();
#Override
public void initialize(URL location, ResourceBundle resources) {
Person.print();
dayArray = new ArrayList<String>(Person.strDays);
tablecols = new TableColumn[dayArray.size()];
System.out.println("tablecols size: " + tablecols.length);
String start = "";
//in each day for the next 60 days
for (int i = 0; i < tablecols.length; i++){
days = new TableColumn<>(dayArray.get(i));
days.setText(dayArray.get(i));
days.setMinWidth(55);
table.getColumns().add(days);
current = dayArray.get(i);
//days.setCellValueFactory(cellData -> new ReadOnlyStringWrapper(cellData.getValue().getEvents().toString()));
//days.setCellValueFactory(cellData -> new ReadOnlyStringWrapper(cellData.getValue().getEvents().get(0).getEvent()));
for (Person p:getPerson()){
if (p.getEvents().size() != 0){
for (int j = 0; j < p.getEvents().size(); j++){
start = p.getEvents().get(j).getStartDate();
String sub = start.substring(0, 5);
// I think we're good here, it gets all the valid days that there's at least one event on
if (current.contains(sub)){
System.out.println(sub);
specific();
}
}
} } }
/*These two do not work here*/
//specific();
//days.setCellValueFactory(cellData -> new ReadOnlyStringWrapper(cellData.getValue().getEvents().get(0).getEvent().toString()));
table.setItems(getPerson());
table.setEditable(true);
table.setStyle("-fx-selection-bar: grey;"); //default cell color
}
/*******************************************************************************************************************************************************************************************************/
/*******************************************************************************************************************************************************************************************************/
public void specific(){ //loops through each column?
days.setCellFactory(new Callback<TableColumn<Person, String>,
TableCell<Person, String>>(){
#Override
public TableCell<Person, String> call(
TableColumn<Person, String> param){
return new TableCell<Person, String>(){
#Override
protected void updateItem(String item, boolean empty){
super.updateItem(item, empty);
if (empty){ //item is null, meaning there's nothing there?
setText(null);
setGraphic(null);
} else {
int currentIndex = indexProperty()
.getValue() < 0 ? 0
: indexProperty().getValue();
ArrayList<Event> type = param //basically person.getEvents()
.getTableView().getItems()
.get(currentIndex).getEvents();
Person person = getTableView().getItems().get(currentIndex);
for (int i = 0; i < type.size(); i++){
String task = type.get(i).getEvent();
/*String day = type.get(i).getStartDate();
String sub = day.substring(0, 5);*/
if (type.get(1).getEvent().equals("International Travel")){
setStyle("-fx-background-color: orange");
setText(task);
}
if (type.get(i).getEvent().equals("PTO")){
setStyle("-fx-background-color: green");
setText(task);
}
else{
setStyle(""); //invisible column but still "filled in"
setText(task);
}
}
}
};
};
}
});
}
public ObservableList<Person> getPerson(){
ObservableList<Person> person = FXCollections.observableArrayList();
ArrayList<Event> eventArray = new ArrayList<Event>();
eventArray.add(new Event("International Travel", "09/22/2018", "09/22/2018"));
eventArray.add(new Event("International Travel", "09/30/2018", "09/30/2018"));
eventArray.add(new Event("PTO", "10/02/2018", "10/02/2018"));
ArrayList<Event> diffArray = new ArrayList<Event>();
diffArray.add(new Event("Personal", "09/22/2018", "09/22/2018"));
diffArray.add(new Event("PTO", "09/30/2018", "09/30/2018"));
diffArray.add(new Event("PTO", "10/02/2018", "10/02/2018"));
person.add(new Person("John", "Smith", "GroupA", eventArray));
person.add(new Person("Karen", "O", "GroupA", eventArray));
person.add(new Person("Jane", "Doe", "GroupB", diffArray));
person.add(new Person("Mike", "Johnson", "GroupA", eventArray));
person.add(new Person("Dukes", "Clan", "GroupB", diffArray));
return person;
}
}
So basically what's going on from the above complete Compilable code is if Dukes has events on 09/22, 09/30, and 10/02, which the event Personal is only on the 22nd, and PTO on the other days of the 30th and 2nd. The 09/22 day column will be blue because the cellFactory will look at the events that Dukes has (which is 3) in that cell, of every cell belonging to Dukes, and then will see that "Oh, she does have a PTO event in her event array, so let's make the whole cell blue". The day columns are important to me and I've thought about putting something like (If PTO && PTO.startDay.equals(dayColumn.getText)), but it'll be ugly and still wouldn't work accurately. I don't know how to be flexible with it. I can only hardcode it to make it look like what I want but it's bad logic, my code is bad logic which is why I'm asking if Hashmap is the way to go before I go through that route, or is there a simple implementation or something I'm overlooking?
Would I need one HashMap or two? because my thinking is that there must be a way to map the person, and day through the event.
Something like this
Mockup
I've searched other links and I think it can be done but I just wanted to get an opinion as to whether a hashmap is needed to accomplish what I want and also on what I've been doing wrong.
Thanks.

How to fill up a TableView with database data

I've been trying to load a TableView with data queried from a database, but can't seem to get it to work.
This is my first attempt at trying to populate a TableView with database query items – in case my code seems mungled and far from good.
The FXML was done via JavaFX SceneBuilder.
This is the database query class:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.TableView;
public class StudentInfo {
static String JDBC_DRIVER = "org.h2.Driver";
static String DB_URL = "jdbc:h2:file:C:/WAKILI/WAKILIdb";
// Database credentials
static final String USER = "sa";
static final String PASS = "";
public static Connection conn = null;
#FXML
private TableView<StudentInfo> lovelyStudents;
private ObservableList data;
// Public static ObservableList<COA> getAllCOA(){
public void getAllstudentInfo() {
Statement st = null;
ResultSet rs;
String driver = "org.h2.Driver";
try {
Class.forName(driver);
conn = DriverManager.getConnection(DB_URL, USER, PASS);
st = conn.createStatement();
String recordQuery = ("SELECT id, KIWI FROM KIWI");
rs = st.executeQuery(recordQuery);
while (rs.next()) {
ObservableList row = FXCollections.observableArrayList();
for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) {
row.add(rs.getString(i));
System.out.println(row);
}
data.add(row);
}
lovelyStudents.setItems(data);
} catch (ClassNotFoundException | SQLException ex) {
// CATCH SOMETHING
}
}
}
This is the FXML script generated via JavaFX scene builder:
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<AnchorPane id="AnchorPane" prefHeight="400.0" prefWidth="700.0" xmlns:fx="http://javafx.com/fxml" fx:controller="wakiliproject.SampleController">
<children>
<TableView prefHeight="400.0" prefWidth="700.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
<columns>
<TableColumn prefWidth="75.0" text="Column X" />
</columns>
</TableView>
</children>
</AnchorPane>
Here is the best solution for the filling data to the tableView From the database.
import java.sql.Connection;
import java.sql.ResultSet;
import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableColumn.CellDataFeatures;
import javafx.scene.control.TableView;
import javafx.stage.Stage;
import javafx.util.Callback;
/**
*
* #author Narayan
*/
public class DynamicTable extends Application{
//TABLE VIEW AND DATA
private ObservableList<ObservableList> data;
private TableView tableview;
//MAIN EXECUTOR
public static void main(String[] args) {
launch(args);
}
//CONNECTION DATABASE
public void buildData(){
Connection c ;
data = FXCollections.observableArrayList();
try{
c = DBConnect.connect();
//SQL FOR SELECTING ALL OF CUSTOMER
String SQL = "SELECT * from CUSTOMer";
//ResultSet
ResultSet rs = c.createStatement().executeQuery(SQL);
/**********************************
* TABLE COLUMN ADDED DYNAMICALLY *
**********************************/
for(int i=0 ; i<rs.getMetaData().getColumnCount(); i++){
//We are using non property style for making dynamic table
final int j = i;
TableColumn col = new TableColumn(rs.getMetaData().getColumnName(i+1));
col.setCellValueFactory(new Callback<CellDataFeatures<ObservableList,String>,ObservableValue<String>>(){
public ObservableValue<String> call(CellDataFeatures<ObservableList, String> param) {
return new SimpleStringProperty(param.getValue().get(j).toString());
}
});
tableview.getColumns().addAll(col);
System.out.println("Column ["+i+"] ");
}
/********************************
* Data added to ObservableList *
********************************/
while(rs.next()){
//Iterate Row
ObservableList<String> row = FXCollections.observableArrayList();
for(int i=1 ; i<=rs.getMetaData().getColumnCount(); i++){
//Iterate Column
row.add(rs.getString(i));
}
System.out.println("Row [1] added "+row );
data.add(row);
}
//FINALLY ADDED TO TableView
tableview.setItems(data);
}catch(Exception e){
e.printStackTrace();
System.out.println("Error on Building Data");
}
}
#Override
public void start(Stage stage) throws Exception {
//TableView
tableview = new TableView();
buildData();
//Main Scene
Scene scene = new Scene(tableview);
stage.setScene(scene);
stage.show();
}
}
Here is the Reference
Thanks..
If Database contains different types of data, not only String, then column type assigning is better to make dynamic:
package sample;
import javafx.application.Application;
import javafx.beans.property.*;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Stage;
import java.sql.*;
import java.util.ArrayList;
import java.util.TimeZone;
//Author: Yerbol
//SQL database "sqlbase_schema" contains a Table "sqlbase_table" with 3 columns: "id" (Integer(INT(11))), "name" (String(VARCHAR(45))), "married" (Boolean(TINYINT(1)));
public class Main extends Application {
private TableView<Person> tableView = new TableView<>();
#Override
public void start(Stage primaryStage) throws SQLException, ClassNotFoundException {
//Show window
buildData();
Parent root = tableView;
primaryStage.setScene(new Scene(root, 300, 275));
primaryStage.show();
}
public void buildData() throws ClassNotFoundException, SQLException {
Connection dbConnection;
//SQL Database connection params
String dbHost = "localhost";
String dbPort = "3306";
String dbUser = "root";
String dbPassword = "12345";
String dbName = "sqlbase_schema";
String dbTableName = "sqlbase_table";
String select = "SELECT * FROM " + dbTableName;
String connectionString = "jdbc:mysql://" + dbHost + ":" + dbPort +"/" + dbName+"?useLegacyDatetimeCode=false&amp&serverTimezone=" + TimeZone.getDefault().getID();
Class.forName("com.mysql.cj.jdbc.Driver");
//Connecting to Database
dbConnection = DriverManager.getConnection(connectionString, dbUser, dbPassword);
//Extracting data from Databasee
ResultSet resultSet = null;
try {
PreparedStatement preparedStatement = dbConnection.prepareStatement(select);
resultSet = preparedStatement.executeQuery();
} catch (SQLException e) {
e.printStackTrace();
}
ObservableList dbData = FXCollections.observableArrayList(dataBaseArrayList(resultSet));
//Giving readable names to columns
for(int i=0 ; i<resultSet.getMetaData().getColumnCount(); i++) {
TableColumn column = new TableColumn<>();
switch (resultSet.getMetaData().getColumnName(i+1)) {
case "id":
column.setText("ID #");
break;
case "name":
column.setText("Person Name");
break;
case "married":
column.setText("Marital Status");
break;
default: column.setText(resultSet.getMetaData().getColumnName(i+1)); //if column name in SQL Database is not found, then TableView column receive SQL Database current column name (not readable)
break;
}
column.setCellValueFactory(new PropertyValueFactory<>(resultSet.getMetaData().getColumnName(i+1))); //Setting cell property value to correct variable from Person class.
tableView.getColumns().add(column);
}
//Filling up tableView with data
tableView.setItems(dbData);
}
public class Person {
IntegerProperty id = new SimpleIntegerProperty(); //variable names should be exactly as column names in SQL Database Table. In case if you want to use <int> type instead of <IntegerProperty>, then you need to use getter/setter procedures instead of xxxProperty() below
StringProperty name = new SimpleStringProperty();
BooleanProperty married = new SimpleBooleanProperty();
public IntegerProperty idProperty() { //name should be exactly like this [IntegerProperty variable name (id) + (Property) = idProperty] (case sensitive)
return id;
}
public StringProperty nameProperty() {
return name;
}
public BooleanProperty marriedProperty() {
return married;
}
public Person(int idValue, String nameValue, boolean marriedValue) {
id.set(idValue);
name.set(nameValue);
married.set(marriedValue);
}
Person(){}
}
//extracting data from ResulSet to ArrayList
private ArrayList dataBaseArrayList(ResultSet resultSet) throws SQLException {
ArrayList<Person> data = new ArrayList<>();
while (resultSet.next()) {
Person person = new Person();
person.id.set(resultSet.getInt("id"));
person.name.set(resultSet.getString("name"));
person.married.set(resultSet.getBoolean("married"));
data.add(person);
}
return data;
}
public static void main(String[] args) {
launch(args);
}
}
In this example SQL database "sqlbase_schema" contains a Table "sqlbase_table" with 3 columns: "id" (Integer(INT(11))), "name" (String(VARCHAR(45))), "married (Boolean(TINYINT(1)));
public TableView queryToTable(String sql) {
TableView result = new TableView();
ObservableList data = FXCollections.observableArrayList();
jdbcTemplate.query(sql, (rs)->{
for(int i=0 ; i<rs.getMetaData().getColumnCount(); i++){
final int j = i;
TableColumn col = new TableColumn(rs.getMetaData().getColumnName(i+1));
col.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<ObservableList,String>,ObservableValue<String>>(){
public ObservableValue<String> call(TableColumn.CellDataFeatures<ObservableList, String> param) {
return new SimpleStringProperty(param.getValue().get(j).toString());
}
});
result.getColumns().addAll(col);
}
while(rs.next()){
ObservableList<String> row = FXCollections.observableArrayList();
for(int i=1 ; i<=rs.getMetaData().getColumnCount(); i++)
row.add(rs.getString(i));
data.add(row);
}
return null;
});
return result;
}

Categories