Sharing screen via Java socket programming - java

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

Related

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>

SplashScreen not closing in javaFX

I am using JavaFX to create an application. SplashScreen opens properly and sets on the screen even after the application opens.
Here are my codes:
Main Class:
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class SplashScreen extends Application {
#Override
public void start(Stage stage) throws Exception {
Parent root=FXMLLoader.load(getClass().getResource("SplashScreenFXML.fxml"));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Controller Class:
package splashscreen;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
public class SplashScreenFXMLController implements Initializable
{
#FXML
private AnchorPane rootPane;
#Override
public void initialize(URL url, ResourceBundle rb)
{
new SplashScreen().start();
}
class SplashScreen extends Thread
{
#Override
public void run()
{
try
{
Thread.sleep(5000);
Platform.runLater(new Runnable(){
#Override
public void run()
{
try {
Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));
Scene scene = new Scene(root);
Stage stage=new Stage();
stage.setScene(scene);
stage.show();
rootPane.getScene().getWindow().hide();
} catch (IOException ex) {
Logger.getLogger(SplashScreenFXMLController.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
} catch (InterruptedException ex) {
Logger.getLogger(SplashScreenFXMLController.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
can Anybody help me with this?
I think rootPane.getScene().getWindow().hide(); this is not working. Is there any otherway that I can hide the SplashScreen Stage?

How to reload the WebView in javafx

I have written code to render my html page( html page is from my local machine) in JavaFX application and now I would like to reload webview whenever the html page(specified) gets modified.
And html modification is done by other application.
Can anyone please let me know how to reload the webview .
Here's the my code :
package view;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.Timer;
import java.util.TimerTask;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.parser.Parser;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.geometry.HPos;
import javafx.geometry.VPos;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Region;
import javafx.scene.paint.Color;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
public class ProgressView extends Application {
private Scene scene;
Browser br = new Browser("E:\\Developer-Job\\test.html");
#Override
public void start(Stage stage) throws Exception {
stage.setTitle("Web View");
scene = new Scene(br,750,500, Color.web("#666970"));
stage.setScene(scene);
//scene.getStylesheets().add("webviewsample/BrowserToolbar.css");
stage.show();
}
class Browser extends Region {
final WebView browser = new WebView();
final WebEngine webEngine = browser.getEngine();
public Browser(String url) {
//apply the styles
getStyleClass().add("browser");
// load the web page
String strXml = "";
String strBuilt ="";
try {
File f = new File(url);
webEngine.load(f.toURI().toURL().toString());
//add the web view to the scene
getChildren().add(browser);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private Node createSpacer() {
Region spacer = new Region();
HBox.setHgrow(spacer, Priority.ALWAYS);
return spacer;
}
#Override protected void layoutChildren() {
double w = getWidth();
double h = getHeight();
layoutInArea(browser,0,0,w,h,0, HPos.CENTER, VPos.CENTER);
}
#Override protected double computePrefWidth(double height) {
return 750;
}
#Override protected double computePrefHeight(double width) {
return 500;
}
}
}
Thanks in advance.
What about checking for changes periodically?
import javafx.animation.Animation;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.geometry.HPos;
import javafx.geometry.VPos;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Region;
import javafx.scene.paint.Color;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
import javafx.util.Duration;
import java.io.File;
import java.io.IOException;
public class ProgressView extends Application {
#Override
public void start(Stage stage) throws Exception {
stage.setTitle("Web View");
Browser br = new Browser("E:\\Developer-Job\\test.html");
Scene scene = new Scene(br, 750, 500, Color.web("#666970"));
stage.setScene(scene);
//scene.getStylesheets().add("webviewsample/BrowserToolbar.css");
stage.show();
}
class Browser extends Region {
final WebView browser = new WebView();
final WebEngine webEngine = browser.getEngine();
public Browser(String url) {
getChildren().add(browser);
//apply the styles
getStyleClass().add("browser");
// load the web page
String strXml = "";
String strBuilt = "";
load(url);
Timeline timeline = new Timeline(new KeyFrame(
Duration.millis(2500),
ae -> load(url)));
timeline.setCycleCount(Animation.INDEFINITE);
timeline.play();
}
private void load(String url) {
try {
File f = new File(url);
webEngine.load(f.toURI().toURL().toString());
//add the web view to the scene
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private Node createSpacer() {
Region spacer = new Region();
HBox.setHgrow(spacer, Priority.ALWAYS);
return spacer;
}
#Override
protected void layoutChildren() {
double w = getWidth();
double h = getHeight();
layoutInArea(browser, 0, 0, w, h, 0, HPos.CENTER, VPos.CENTER);
}
#Override
protected double computePrefWidth(double height) {
return 750;
}
#Override
protected double computePrefHeight(double width) {
return 500;
}
}
}
I've found an answer using below code:
webEngine.documentProperty().addListener(new ChangeListener<Document>() {
#Override
public void changed(ObservableValue<? extends Document> observableValue, Document document, Document newDoc) {
if (newDoc != null) {
//webEngine.documentProperty().removeListener(this);
try {
webEngine.load(f.toURI().toURL().toString());
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});

Getting database data to TableView

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;

Categories