Error of UDP server in javaFx - javafx

I made the source code of UDP server. the task of code shows figure when it received data via UDP communication. I used thread to receive data from other PC via UDP communication.
I use udp test tool from the other PC to check the code.
But, when startup my jar of source code in first, then the udp test tool can't bind the port .
what is the problem of my source code?
(In case that I set different values as the bind's port and send port in other PC's udp test tool,then my source code shows successfully the figure.)
package javafxapplication15;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonBuilder;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.FlowPaneBuilder;
import javafx.scene.layout.HBox;
import javafx.scene.layout.HBoxBuilder;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.layout.VBoxBuilder;
import javafx.stage.Stage;
import javafx.stage.StageBuilder;
import java.io.*;
import java.net.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.concurrent.ScheduledService;
import javafx.concurrent.Service;
import javafx.concurrent.Task;
import javafx.geometry.Pos;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.LabelBuilder;
import javafx.scene.control.ProgressIndicator;
import javafx.scene.control.TextField;
import javafx.scene.control.TextFieldBuilder;
import javafx.scene.layout.GridPane;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.TextAlignment;
import javafx.util.Duration;
import sun.misc.HexDumpEncoder;
public class JavaFXApplication15 extends Application {
public DatagramSocket receivesocket;
public DatagramPacket receivepacket;
public DatagramSocket sendsocket;
public DatagramPacket sendpacket;
public InetSocketAddress remoteAdress;
public Label label;
public Label label_IP;
public Label label_IP_in;
public TextField tx_IP;
public Label label_SENDPORT;
public Label label_SENDPORT_in;
public Label label_RECEIVEPORT;
public Label label_RECEIVEPORT_in;
public Label label_status;
public TextField tx_SENDPORT;
public TextField tx_RECEIVEPORT;
public Button bt_co;
public Button bt1;
public Button bt2;
public Button bt_play ;
public ObservableList<String> play_num=null;
public ComboBox<String> comboBox;
private String message;
private XYChart.Series series;
private Timeline timer;
private ProgressIndicator indicator;
private static String s = null;
private static String IP = "192.168.101.30";
private static Integer RECEIVEPORT = 8084;
public double time_counter=0.0;
public double torque_receive_value=0.0;
public byte[] torque_Hex;
private String text;
private byte[] buf;
#Override
public void start(Stage stage) throws Exception{
/* timer */
timer = new Timeline(new KeyFrame(Duration.millis(1000), new EventHandler<ActionEvent>(){
#Override
public void handle(ActionEvent event) {
time_counter = time_counter+1;
}
}));
timer.setCycleCount(Timeline.INDEFINITE);
timer.play();
/* Figure*/
stage.setTitle("Line Chart Sample");
//defining the axes
final NumberAxis xAxis = new NumberAxis();
final NumberAxis yAxis = new NumberAxis();
xAxis.setLabel("Time [s]");
yAxis.setLabel("Force [N]");
//creating the chart
final LineChart<Number,Number> lineChart =
new LineChart<Number,Number>(xAxis,yAxis);
lineChart.setTitle("Receive Data");
//defining a series
series = new XYChart.Series();
series.setName("Torque");
series.getData().add(new XYChart.Data(0.0,0.0));
lineChart.getData().add(series);
VBox root = VBoxBuilder.create().spacing(25).children(lineChart).build();
Scene scene = new Scene(root);
recieve_UDP();
stage = StageBuilder.create().width(640).height(640).scene(scene).title("").build();
stage.show();
}
private void recieve_UDP() throws SocketException, IOException {
ScheduledService<Boolean> ss = new ScheduledService<Boolean>()
{
#Override
protected Task<Boolean> createTask()
{
Task<Boolean> task = new Task<Boolean>()
{
#Override
protected Boolean call() throws Exception
{
receivesocket = null;
byte[] receiveBuffer = new byte[1024];
receivepacket = new DatagramPacket(receiveBuffer, receiveBuffer.length);
receivesocket = new DatagramSocket(RECEIVEPORT);
receivesocket.receive(receivepacket);
message = new String(receivepacket.getData(),0, receivepacket.getLength());
torque_Hex = receivepacket.getData();
System.out.println(message);
if(message != "Status:Wait"){
Platform.runLater( () ->label_status.setText("Status:Done"));
/* show Figure */
Platform.runLater( () -> series.getData().add(new XYChart.Data(time_counter,Double.parseDouble( message))));
}
receivesocket.close();
return true;
};
};
return task;
}
};
ss.start();
}
public static void main(String[] args) {
launch(args);
}
}

Related

Request fix functionality

MY TASK : Write a JavaFX GUI application that allows the user to pick a set of pizza toppings using a set of check boxes. Assuming each topping cost 50 cents, and a plain pizza costs $10, display the cost of the pizza. Note that, once a topping is checked or unchecked, the cost of pizza should update automatically.
FIX REQUEST : my pizza cost calculator fails to add cost for topping properly
For example, Extracheese checked and unchecked resulted in below base price $10 (ie; $7)
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.scene.layout.HBox;
import javafx.scene.transform.Scale;
import javafx.stage.Stage;
import javafx.scene.text.Text;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
class PizzaCost extends VBox {
private CheckBox ExtraCheeseCheckBox;
private CheckBox GreenPepperCheckBox;
private Label TotalPizzaCost;
public double pizzaCost = 10.0;
public PizzaCost(){
Font font = new Font(13);
ExtraCheeseCheckBox = new CheckBox("Extra Cheese");
ExtraCheeseCheckBox.setOnAction(this::processCheckBoxAction);
GreenPepperCheckBox = new CheckBox("GreenPepper");
GreenPepperCheckBox.setOnAction(this::processCheckBoxAction);
TotalPizzaCost = new Label(pizzaCost +"");
TotalPizzaCost.setFont(font);
HBox options = new HBox(ExtraCheeseCheckBox,GreenPepperCheckBox);
getChildren().addAll(options,TotalPizzaCost);
}
public void processCheckBoxAction (ActionEvent event){
if (ExtraCheeseCheckBox.isSelected()){
pizzaCost += 0.5;
}
else {
pizzaCost -= 0.5;
}
TotalPizzaCost.setText(pizzaCost+"");
}
}
The following code works for me. The pizza cost never goes below $10.
import java.text.NumberFormat;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.stage.Stage;
public class PizzaCost extends Application {
private static final double TOPPING_COST = 0.5d;
private static final NumberFormat COST_FORMAT = NumberFormat.getCurrencyInstance();
private static final String PIZZA_COST = "Pizza Cost: ";
private double pizzaCost = 10.0d;
private Label totalPizzaCostLabel;
#Override
public void start(Stage primaryStage) throws Exception {
CheckBox extraCheesCheckBox = getCheckBox("Extra Cheese");
CheckBox greenPepperCheckBox = getCheckBox("Green Pepper");
HBox hBox = new HBox(20.0d, extraCheesCheckBox, greenPepperCheckBox);
totalPizzaCostLabel = new Label(PIZZA_COST + COST_FORMAT.format(pizzaCost));
totalPizzaCostLabel.setFont(new Font(13.0d));
VBox root = new VBox(20.0d, hBox, totalPizzaCostLabel);
root.setAlignment(Pos.CENTER);
root.setPadding(new Insets(40.0d));
Scene scene = new Scene(root);
primaryStage.setScene(scene);
primaryStage.setTitle("Pizza Cost");
primaryStage.show();
}
private CheckBox getCheckBox(String text) {
CheckBox cb = new CheckBox(text);
cb.setOnAction(this::processCheckBoxAction);
return cb;
}
private void processCheckBoxAction(ActionEvent event) {
CheckBox cb = (CheckBox) event.getSource();
if (cb.isSelected()) {
pizzaCost += TOPPING_COST;
}
else {
pizzaCost -= TOPPING_COST;
}
totalPizzaCostLabel.setText(PIZZA_COST + COST_FORMAT.format(pizzaCost));
}
public static void main(String[] args) {
launch(args);
}
}

Java fx event handler

Why my code is not running? How am I going to display an image on the interface when clicked "add image"?
import javafx.stage.Stage;
import javafx.scene.*;
import javafx.application.Application;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
public class GUIProject extends Application{
/**
* #param args the command line arguments
*/
public void start (Stage stage) throws Exception
{
Pane bPane = new Pane();
Button btOK = new Button("OK");
OKAction OKact = new OKAction();
btOK.setOnAction(OKact);
Button addImage = new Button("Add Image");
isAdd addimage = new isAdd();
addImage.setOnAction(addimage);
//bPane.getChildren().add(btOK);
bPane.getChildren().add(addImage);
Scene scene = new Scene(bPane);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
// TODO code application logic here
Application.launch(args);
}
}
import java.io.FileInputStream;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.StackPane;
public class Pane extends StackPane {
public void addImage() throws Exception
{
Image logo = new Image(new FileInputStream("logo.jpg"));
ImageView logoView = new ImageView(logo);
this.getChildren().add(logoView);
}
}
import java.io.FileInputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
class isAdd implements EventHandler<ActionEvent>{
public void handle(ActionEvent event)
{
try {
Pane.displayImage();
}
catch (Exception ex) {
System.out.println("Error");;
}
}
}
It keep showing static method cannot with non-static method, how can I solve that?
Is there any website can learn javafx event handler?

Java FX Circle Image

I hope you can help me. I'm trying to round a image retrieved from my database. In the next image you can see the image is correctly displayed in a imageview. User selects a new item in the table and the image change to display the correct image, this is working, no problems here.
This is the program
I try with this code in the gestionarEventos :
imgfotovisi.imageProperty().bind(imageRetrievalService.valueProperty());
Image im = imgfotovisi.getImage();
circulo.setFill(new ImagePattern(im));
But java say :
... 58 more
Caused by: java.lang.NullPointerException: Image must be non-null.
at javafx.scene.paint.ImagePattern.<init>(ImagePattern.java:235)
The program runs if I delete the lines below the
imgfotovisi.imageProperty().bind(imageRetrievalService.valueProperty());
line.
When it runs, I don't know why says the image is null, when I can see clearly there.
This is ver_visitantes class:
import java.net.URL;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.ResourceBundle;
import java.util.function.Predicate;
import javafx.beans.property.ReadOnlyStringWrapper;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.collections.transformation.SortedList;
import javafx.concurrent.Service;
import javafx.concurrent.Task;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.InputEvent;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.paint.ImagePattern;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
public class ver_visitantes implements Initializable {
#FXML private TableView<visitantes> tbvisitantes;
#FXML private TableColumn<visitantes, String> clcedula,clnombres,clapellidos,clapartamento,clcelular,clobservaciones;
#FXML private ImageView imgfotovisiact,imgfotoact,imgfotovisi,imgfoto;
#FXML private TextField txtcedula,txtnombres,txtapto,txtapellidos,txtapt,txtcelular,txtobservaciones;
#FXML private Label lblinfovisiact,lblusuario,lblstatusvisi;
#FXML private Circle circulo;
private ObservableList<visitantes> visitorlist;
#Override
public void initialize(URL arg0, ResourceBundle arg1) {
ConexionSQL cnt = new ConexionSQL();
cnt.conexion();
visitorlist = FXCollections.observableArrayList();
visitantes.llenarlistavisitas(cnt.conexion(), visitorlist);
tbvisitantes.setItems(visitorlist);// llenar table view con la lista
clcedula.setCellValueFactory(cellData -> new ReadOnlyStringWrapper(cellData.getValue().getcedula()));
clnombres.setCellValueFactory(cellData -> new ReadOnlyStringWrapper(cellData.getValue().getnombres()));
clapellidos.setCellValueFactory(cellData -> new ReadOnlyStringWrapper(cellData.getValue().getapellidos()));
clapartamento.setCellValueFactory(cellData -> new ReadOnlyStringWrapper(cellData.getValue().getapartamento()));
clcelular.setCellValueFactory(cellData -> new ReadOnlyStringWrapper(cellData.getValue().getcelular()));
clobservaciones.setCellValueFactory(cellData -> new ReadOnlyStringWrapper(cellData.getValue().getobservaciones()));
gestionarEventos();
tbvisitantes.getSelectionModel().selectFirst();
}
public void gestionarEventos() {
tbvisitantes.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<visitantes>() {
#Override
public void changed(ObservableValue<? extends visitantes> arg0, visitantes valorAnterior,
visitantes valorSeleccionado) {
imgfoto.setVisible(false);
btnmodificar.setDisable(false);
btncancelar.setDisable(false);
btneliminar.setDisable(false);
imageRetrievalService.restart();
if (valorSeleccionado != null) {
txtcedula.setText(String.valueOf(valorSeleccionado.getcedula()));
txtnombres.setText(valorSeleccionado.getnombres());
txtapellidos.setText(valorSeleccionado.getapellidos());
txtapto.setText(String.valueOf(valorSeleccionado.getapartamento()));
txtcelular.setText(String.valueOf(valorSeleccionado.getcelular()));
txtobservaciones.setText(String.valueOf(valorSeleccionado.getobservaciones()));
}
}
});
imgfotovisi.imageProperty().bind(imageRetrievalService.valueProperty());
}
private final Service<Image> imageRetrievalService = new Service<Image>() {// cargar imagen en visitantes
#Override
protected Task<Image> createTask() {
final String id;
final visitantes visitante = tbvisitantes.getSelectionModel().getSelectedItem();
if (visitante == null) {
id = null;
} else {
id = visitante.getcedula();
}
return new Task<Image>() {
#Override
protected Image call() throws Exception {
if (id == null) {
return null;
}
return visitante.getImageById(id);
}
};
}
};
}
this is the visitantes class,called from the imageRetrievalService to get the image:
package application;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.ObservableList;
import javafx.scene.image.Image;
public class visitantes {
private StringProperty cedula;
private StringProperty nombres;
private StringProperty apellidos;
private StringProperty apartamento;
private StringProperty celular;
private StringProperty observaciones;
public visitantes(String cedula,String nombres,String apellidos,String apartamento,String celular,String observaciones){
this.cedula = new SimpleStringProperty(cedula);
this.nombres = new SimpleStringProperty(nombres);
this.apellidos = new SimpleStringProperty(apellidos);
this.apartamento = new SimpleStringProperty(apartamento);
this.celular = new SimpleStringProperty(celular);
this.observaciones = new SimpleStringProperty(observaciones);
}
public String getnombres(){
return nombres.get();
}
public void setnombres(String nombres){
this.nombres = new SimpleStringProperty(nombres);
}
public String getcedula(){
return cedula.get();
}
public void setcedula(String cedula){
this.cedula = new SimpleStringProperty(cedula);
}
public String getapellidos(){
return apellidos.get();
}
public void setapellidos(String apellidos){
this.apellidos = new SimpleStringProperty(apellidos);
}
public String getapartamento(){
return apartamento.get();
}
public void setapartamento(String apartamento){
this.apartamento = new SimpleStringProperty(apartamento);
}
public String getcelular(){
return celular.get();
}
public void setcelular(String celular){
this.celular = new SimpleStringProperty(celular);
}
public Image getImageById(String id) throws SQLException, IOException {
try (
ConexionSQL cn = new ConexionSQL();
Connection con = cn.conexion();
PreparedStatement ps = con.prepareStatement(
"SELECT foto_visi FROM visitantes WHERE cedula_visi = ?");
) {
ps.setString(1, id);
ResultSet results = ps.executeQuery();
Image img = null ;
if (results.next()) {
Blob foto = results.getBlob("foto_visi");
InputStream is = foto.getBinaryStream();
img = new Image(is) ; // false = no background loading
is.close();
}
results.close();
return img ;
} catch (Throwable e) {
String info = e.getMessage();
System.out.println(info);
}
return null;
}
}
I think the problem is here:
imgfotovisi.imageProperty().bind(imageRetrievalService.valueProperty());
I don't know if the retrieved image is loaded in the imageivew in this line. Looks like yes, but if I do
Image im = imgfotovisi.getImage();
Java says it is null. Then I can't get the image into the circle.
Thanks in advance :)
bind isn't going to load an image itself, it will just bind so that one variable will change when the source changes (in this case the value property of the service), which isn't going to happen straight away as the service is running asynchronously. So, if you query the value straight away after issuing the bind statement, you won't get the result you are expecting, as the source hasn't yet changed.
Instead you need to take action only once the image is actually available.
For instance:
imageRetrievalService.valueProperty().addListener((obs, oldVal, newVal) ->
if (newVal != null)
circulo.setFill(new ImagePattern(newVal))
);
Or, if you don't want a direct linkage to the service, and given that the imgfotovsi image property is already bound to the service value:
imgfotovisi.imageProperty().addListener((obs, oldVal, newVal) ->
if (newVal != null)
circulo.setFill(new ImagePattern(newVal))
);

Javafx split pane with treeview

Please help me to add item from addproject controller to project controller. I want to add item from addprojects controller to projectscontroller method. Please guide me to resolve this. please guide to dynamically change the right side split pane view and add tree item in treeview and show to user.
package com.define.controller;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.event.Event;
//import org.apache.commons.io.FileUtils;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Tab;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.HBox;
import javafx.stage.DirectoryChooser;
import javax.naming.Context;
import testapp.TestApp;
public class ProjectsController implements Initializable{
// #FXML private HBox fileList;
#FXML TreeView<String> Maintree ;
#FXML private AnchorPane Anchorpane;
File destinationFolder;
//Image img = new Image();
//private final Node rootIcon = new ImageView(img);
/* private final Node rootIcon = new ImageView(
new Image(getClass().getResourceAsStream("G:\\workspace\\DefineApp\\src\\images\\folder.png")));*/
File file = new File("D:\\DefineApp\\src\\images\\folder.png");
Image image = new Image(file.toURI().toString(),20,20,false,false);
private Node rootIcon = new ImageView(image);
#Override
public void initialize(URL location, ResourceBundle resources) {
File currentDir = new File("D:\\DefineApp\\src\\Documents"); // current directory
rootItem.setExpanded(true);
Maintree.setShowRoot(false);
Maintree.setRoot(rootItem);
findFiles(currentDir);
try {
changeView();
} catch (IOException ex) {
Logger.getLogger(ProjectsController.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void UploadFiles() throws IOException{
DirectoryChooser directory = new DirectoryChooser();
directory.setTitle("Choose Directory");
final File selectedDirectory = directory.showDialog(null);
File sourcefolder = new File(selectedDirectory.getAbsolutePath());
String projectName = "Symbiance";
String studyName = "study1";
destinationFolder = new File("G:\\workspace\\DefineApp\\src\\"+projectName+"\\"+studyName);
if(!destinationFolder.exists()){
destinationFolder.mkdirs();
if(destinationFolder.isDirectory()){
// FileUtils.copyDirectory(sourcefolder, destinationFolder);
System.out.println("Files Copied Successfully");
}
}else{
if(destinationFolder.isDirectory()){
//FileUtils.copyDirectory(sourcefolder, destinationFolder);
System.out.println("Files Copied Successfully");
}
}
//Method call for list the files
listFiles();
}
public void listFiles(){
//fileList.setPadding(new Insets(15, 12, 15, 12));
//fileList.setSpacing(10);
File[] listOfFiles = destinationFolder.listFiles();
CheckBox[] cbs = new CheckBox[listOfFiles.length];
int i=0;
for (File file : listOfFiles) {
CheckBox cbox = cbs[i]= new CheckBox(file.getName());
i++;
}
//fileList.getChildren().addAll(cbs);
}
TreeItem<String> rootItem = new TreeItem<String>("Root");
public void findFiles(File currentDir){
//rootItem.setGraphic(rootIcon);;
TreeItem<String> subfolder;
// parent = new TreeItem<String> (parent.getValue(),rootIcon);
System.out.println("1");
File folder = new File(currentDir.getAbsolutePath());
File[] listOfFiles = folder.listFiles();
for (File file:listOfFiles) {
if(file.isDirectory()){
subfolder = new TreeItem<String> (file.getName());
rootItem.getChildren().add(subfolder);
File subFolderName = new File(file.getAbsolutePath());
File[] subFolderFiles = subFolderName.listFiles();
for(File f:subFolderFiles){
TreeItem<String> it= new TreeItem<String>(f.getName());
subfolder.getChildren().add(it);
}
}
}
}
public void changeView() throws IOException{
System.out.println("change view is called");
Anchorpane.getChildren().add(TestApp.getInstance().designChooser("com/define/views/AddProject.fxml"));
//setContent();
}
public void addProject(String name,Event e){
rootItem.getChildren().add(new TreeItem(name));
System.out.println("test check");
}
}
another controller;
package com.define.controller;
import java.io.File;
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.control.Button;
import javafx.scene.control.RadioButton;
import javafx.scene.control.TextField;
import javafx.scene.control.ToggleGroup;
import javafx.scene.control.TreeItem;
import javafx.scene.text.Text;
public class AddProjectController implements Initializable{
#FXML Button yesbutton;
#FXML RadioButton projectYesRadio;
#FXML RadioButton projectNORadio;
#FXML TextField projectId;
#FXML TextField projectName;
final ToggleGroup Projectgroup = new ToggleGroup();
final File baseFolder = new File("D:\\DefineApp\\src\\Documents");
File projectFolder;
#Override
public void initialize(URL location, ResourceBundle resources) {
projectYesRadio.setToggleGroup(Projectgroup);
projectNORadio.setToggleGroup(Projectgroup);
projectYesRadio.setSelected(true);
}
public void addProject(ActionEvent e){
projectFolder = new File("D:\\DefineApp\\src\\Documents\\"+projectName.getText());
projectFolder.mkdir();
ProjectsController pt = new ProjectsController();
pt.addProject(projectName.getText(),e);
//System.out.println(projectController.Maintree.getRoot());
//.rootItem.getChildren().add(new TreeItem(projectName.getText()));
//projectController.findFiles(baseFolder);
System.out.println("test check");
}
public void radiocalled(){
//yesbutton.setVisible(false);
}
}

Real-time LineChart JavaFx

I have a problem with my GUI. I am trying to create a Gui which displays some analog values stored by the Arduino microcontroller. I am able to store all data I want in an array. Now I am using SceneBuilder and JavaFx to plot the arrays of this analog signal and I see the real signal but the graph is autoscaling and scattering . I would like to have more something like the following:
Advanced Stock Line Chart example in JAVAFX
JavaFX Example
Here is my code. The function updateGraph1(...) is called everytime that I receive a value which can update the graph.
package de.zft.degreen.view;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.Set;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.ValueAxis;
import javafx.scene.chart.XYChart;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
public class Gui extends Application implements Runnable, Initializable {
#FXML
private static LineChart<Number,Number> graph1;
public static XYChart.Series<Number, Number> series;
private ChangeListener changeListener;
private static Scene scene;
public Gui() {
series = new XYChart.Series<>();
series.setName("bye");
}
public ChangeListener getChangeListener() {
return changeListener;
}
public void setChangeListener(ChangeListener changeListener) {
this.changeListener = changeListener;
}
#Override
public void start(Stage primaryStage) throws Exception {
System.out.println("Start start");
primaryStage.setTitle("DEGREEN GUI");
System.out.println("Before");
Pane myPane = FXMLLoader.load(getClass().getResource("Gui2.fxml"));
System.out.println("After");
System.out.println("Step1");
scene = new Scene(myPane);
System.out.println("Step2");
primaryStage.setScene(scene);
System.out.println("Step3");
primaryStage.show();
System.out.println("End start");
}
private void init(Stage primaryStage){
System.out.println("Start Init");
}
#FXML
public void updateGraph1(Long long1, int v){
System.out.println("Start updateGraph1"+series.getName());
final int q = v;
final long long2 = long1;
Platform.runLater(new Runnable() {
#Override
public void run() {
add2Series(long2,q,100);
}
});
System.out.println("End updateGraph1");
}
#Override
public void run() {
System.out.println("Gui Initialized");
launch();
System.out.println("Gui Ended");
}
#FXML
public void initialize(URL arg0, ResourceBundle arg1) {
System.out.println("Start Initialize"+series.getName());
series = new XYChart.Series<Number,Number>();
series.setName("Voltage DE1");
graph1.getData().add(series);
graph1.setAnimated(false);
System.out.println("End Initialize"+series.getName());
}
#FXML
protected static void add2Series(Number x, Number y, int displayedSize) {
int seriesSize = series.getData().size();
if (seriesSize >= displayedSize) {
series.getData().remove(0);
}
series.getData().add(new XYChart.Data<Number,Number>(x,y));
}
}
Someone Can help me please?
Take a look at this sample . The visible categories are managed in runtime so that only last ten added are visible.

Resources