Javafx application (calculator) isn't working on other computers - javafx

I have made a calculator using javafx(I am a beginner). It worked fine on my computer. When I shared with my friend, only the stage was loaded like this...
Whereas, in computer...
[![This is it, a simple calculator][2]][2]
As a java programmer, this is my first project. It would be great, if you help me out with this...
Well, I have created this with Netbeans IDE, and there are three classes. Calculate.java(to calculate) , JavaFXApplication8.java(extends application) , and FXMLDocumentController.java(to control FXML file)
public class JavaFXApplication8 extends Application {
#Override
public void start(Stage stage) throws Exception {
stage.initStyle(StageStyle.UNIFIED);
stage.setMaxHeight(350);
stage.setMaxWidth(360);
stage.setResizable(false);
Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));
stage.setTitle("Calculator");
Scene scene = new Scene(root);
Image icon=new Image("Calculator-icon.png");
stage.getIcons().add(icon);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
public class FXMLDocumentController implements Initializable {
public static String a="";
private void SetLabel(ActionEvent event) {
result.setText(a);
}
#FXML
private void OnePressed(ActionEvent event) {
a=a.concat("1");
result.setText(a);
}
#FXML
private void TwoPressed(ActionEvent event) {
a=a.concat("2");
result.setText(a);
}
#FXML
private void ThreePressed(ActionEvent event) {
a=a.concat("3");
result.setText(a);
}
#FXML
private void FourPressed(ActionEvent event) {
a=a.concat("4");
result.setText(a);
}
#FXML
private void FivePressed(ActionEvent event) {
a=a.concat("5");
result.setText(a);
}
#FXML
private void SixPressed(ActionEvent event) {
a=a.concat("6");
result.setText(a);
}
#FXML
private void SevenPressed(ActionEvent event) {
a=a.concat("7");
result.setText(a);
}
#FXML
private void EightPressed(ActionEvent event) {
a=a.concat("8");
result.setText(a);
}
#FXML
private void NinePressed(ActionEvent event) {
a=a.concat("9");
result.setText(a);
}
#FXML
private void ZeroPressed(ActionEvent event) {
a=a.concat("0");
result.setText(a);
}
#FXML
private void PointPressed(ActionEvent event) {
a=a.concat(".");
result.setText(a);
}
#FXML
private void DelPressed(ActionEvent event) {
a=Calculate.Del(a);
result.setText(a);
}
#FXML
private void ACPressed(ActionEvent event) {
a="";
result.setText(a);
}
#FXML
private void AddPressed(ActionEvent event) {
a=a.concat("+");
result.setText(a);
}
#FXML
private void SubtractPressed(ActionEvent event) {
a=a.concat("-");
result.setText(a);
}
#FXML
private void MultiplyPressed(ActionEvent event) {
a=a.concat("*");
result.setText(a);
}
#FXML
private void DividePressed(ActionEvent event) {
a=a.concat("/");
result.setText(a);
}
#FXML
private void PercentPressed(ActionEvent event) {
if(a.contains("/")){
a=Calculate.divide(a);
float percent=Float.valueOf(a);
percent*=100;
result.setText(String.valueOf(percent).concat("%"));
}
else{
result.setText("Syntax error");
}
}
#FXML
private void Result(ActionEvent event) {
try {
for (int i = 1; i < a.length(); i++) {
char ch=a.charAt(i);
switch (ch) {
case '+':
a=Calculate.add(a);
result.setText(" = "+a);
break;
case '-':
a=Calculate.subtract(a);
result.setText(" = "+a);
break;
case '*':
a=Calculate.multiply(a);
result.setText(" = "+a);
break;
case '/':
a=Calculate.divide(a);
result.setText(" = "+a);
break;
default:
break;
}
}
} catch (Exception e) {
result.setText("Syntax error");
}
}
#Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
}
#FXML
private void SetLabel(MouseEvent event) {
}
}
public class Calculate {
public static String result;
public static String add(String s){
int d=0;
String fist="";
String secon="";
char ch='+';
for (int i = 0; i < s.length(); i++) {
char ch2=s.charAt(i);
if(ch==ch2){
fist=s.substring(0, i);
secon=s.substring(i+1, s.length());
}
}
float a=Float.valueOf(fist);
float b=Float.valueOf(secon);
float c=a+b;
if(String.valueOf(c).endsWith(".0")){
result=String.valueOf(c).substring(0, String.valueOf(c).length()-2);
}
else{
result=String.valueOf(c);
}
return result;
}
public static String subtract(String s){
String fist="";
String secon="";
char ch='-';
for (int i = 0; i < s.length(); i++) {
char ch2=s.charAt(i);
if(ch==ch2){
fist=s.substring(0, i);
secon=s.substring(i+1, s.length());
}
}
float a=Float.valueOf(fist);
float b=Float.valueOf(secon);
float c=a-b;
if(String.valueOf(c).endsWith(".0")){
result=String.valueOf(c).substring(0, String.valueOf(c).length()-2);
}
else{
result=String.valueOf(c);
}
return result;
}
public static String multiply(String s){
String fist="";
String secon="";
char ch='*';
for (int i = 0; i < s.length(); i++) {
char ch2=s.charAt(i);
if(ch==ch2){
fist=s.substring(0, i);
secon=s.substring(i+1, s.length());
}
}
float a=Float.valueOf(fist);
float b=Float.valueOf(secon);
float c=a*b;
if(String.valueOf(c).endsWith(".0")){
result=String.valueOf(c).substring(0, String.valueOf(c).length()-2);
}
else{
result=String.valueOf(c);
}
return result;
}
public static String divide(String s){
String fist="";
String secon="";
char ch='/';
for (int i = 0; i < s.length(); i++) {
char ch2=s.charAt(i);
if(ch==ch2){
fist=s.substring(0, i);
secon=s.substring(i+1, s.length());
}
}
float a=Float.valueOf(fist);
float b=Float.valueOf(secon);
float c=a/b;
if(String.valueOf(c).endsWith(".0")){
result=String.valueOf(c).substring(0, String.valueOf(c).length()-2);
}
else{
result=String.valueOf(c);
}
return result;
}
public static String Del(String s){
int len=s.length();
s=s.substring(0, len-1);
return s;
}
}
It became a little bit lengthy, but please go through it. It is damn easy for anyone who can attempt answering it.

Related

Using a static nested class insted of toString

I have this task:
"We do not want to rely on us Currency their toString() for how a currency is displayed in list our. We will be able to set this up ourselves.
Create a static nested class called "Currency Cell" in ValutaOversikController as extender List Cell <Value>.
Override methods updateItem (Currency and Currency, boolean empty).
Set how a currency should be presented in the list e.g. "Country - Currency Code"
Then put CellFactory for our ListView, which returns an instance of the new Currency Cell class."
I started to make the last method in Controller, but don't know if this is correct. As of now this is what I have:
public class Controller {
#FXML
private ComboBox<Valuta> listeMedValutaerEn, listeMedValutaerTo;
#FXML
private ComboBox<Sorteringen> listeMedSortering;
#FXML
private TextField textFieldValutaerEn, textFieldValutaerTo;
#FXML
private ImageView imageViewValutaerEn, imageViewValutaerTo;
#FXML
public void initialize() {
listeMedValutaerEn.setItems(DataHandler.hentValutaData());
listeMedValutaerTo.setItems(DataHandler.hentValutaData());
listeMedSortering.setItems(DataHandler.hentSorteringsData());
listeMedValutaerEn.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<Valuta>() {
#Override
public void changed(ObservableValue<? extends Valuta> observableValue, Valuta gammelValuta, Valuta nyValuta) {
fyllUtValutaEn(nyValuta);
}
});
listeMedValutaerTo.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<Valuta>() {
#Override
public void changed(ObservableValue<? extends Valuta> observableValue, Valuta gammelValuta, Valuta nyValuta) {
fyllUtValutaTo(nyValuta);
}
});
listeMedSortering.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<Sorteringen>() {
#Override
public void changed(ObservableValue<? extends Sorteringen> observableValue, Sorteringen gammelSortering, Sorteringen nySortering) {
sortere(nySortering);
}
});
}
private void sortere(Sorteringen nySortering) {
ObservableList<Valuta> valutaSomSkalSorteres = DataHandler.hentValutaData();
CompareToValuta sortere = new CompareToValuta(nySortering.getSorteringsKode());
Collections.sort(valutaSomSkalSorteres, sortere);
listeMedValutaerEn.setItems(valutaSomSkalSorteres);
listeMedValutaerTo.setItems(valutaSomSkalSorteres);
}
private void fyllUtValutaEn(Valuta enValuta) {
if (enValuta != null) {
Image flaggEn = new Image("https://www.countryflags.io/" + enValuta.getLandskode() + "/shiny/64.png");
imageViewValutaerEn.setImage(flaggEn);
}
}
private void fyllUtValutaTo(Valuta enValuta) {
if (enValuta != null) {
Image flaggTo = new Image("https://www.countryflags.io/" + enValuta.getLandskode() + "/shiny/64.png");
imageViewValutaerTo.setImage(flaggTo);
}
}
#FXML
private void buttonBeregn(ActionEvent event) {
Integer valutaAntall = Integer.valueOf(textFieldValutaerEn.getText());
double valutaNrEn = listeMedValutaerEn.getSelectionModel().getSelectedItem().getValutakurs();
double valutaNrTo = listeMedValutaerTo.getSelectionModel().getSelectedItem().getValutakurs();
double valutaResultat = valutaAntall * (valutaNrEn / valutaNrTo);
textFieldValutaerTo.setText(String.valueOf(valutaResultat));
}
private static ListCell<Valuta> ValutaCelle() {
ListCell<Valuta> tja = new ListCell<>();
return tja;
}
}
Class DataHandler:
public class DataHandler {
private final static ObservableList<Valuta> valutaListe = FXCollections.observableArrayList();
private final static ObservableList<Sorteringen> sorteringsListe = FXCollections.observableArrayList();
public static ObservableList<Sorteringen> hentSorteringsData() {
if (sorteringsListe.isEmpty()) {
sorteringsListe.add(new Sorteringen("Sortere alfabetisk på land synkende", 1));
sorteringsListe.add(new Sorteringen("Sortere alfabetisk på land stigende", 2));
sorteringsListe.add(new Sorteringen("Sortere på valutakode, stigende", 3));
sorteringsListe.add(new Sorteringen("Sortere på valutakode, synkende", 4));
}
return sorteringsListe;
}
public static ObservableList<Valuta> hentValutaData() {
if (valutaListe.isEmpty()) {
valutaListe.addAll(genererValutaData());
}
return valutaListe;
}
private static ArrayList<Valuta> genererValutaData() {
File kilden = new File("src/no/hiof/aleksar/oblig5/valutakurser.csv");
ArrayList<Valuta> valutaerFraFiler = lesFraCSVFil(kilden);
return valutaerFraFiler;
}
private static ArrayList<Valuta> lesFraCSVFil(File filSomLesesFra) {
ArrayList<Valuta> valutaerFraFil = new ArrayList<>();
try (BufferedReader bufretLeser = new BufferedReader(new FileReader(filSomLesesFra))) {
String linje;
while( (linje = bufretLeser.readLine()) != null ){
String[] deler = linje.split(";");
Valuta enValuta = new Valuta(deler[0], deler[1], deler[2], Double.parseDouble(deler[3]));
valutaerFraFil.add(enValuta);
}
} catch (IOException e) {
System.out.println(e);
}
return valutaerFraFil;
}
}

Trying to include carousel with a timer in javafx

Trying to include carousel with a timer in javafx.
public class Controller {
#FXML
private ImageView imageslidder;
#FXML
private ImageView left;
#FXML
private ImageView right;
#FXML
private Circle picone;
#FXML
private Circle pictwo;
#FXML
private Circle picthree;
int imag_index = 0;
String images[] = new String []{"sample/one.jpg", "sample/two.jpg", "sample/three.jpg"};
void nextImage() {
switch (imag_index) {
case 0:
setStroke(picone);
resetStroke(pictwo);
resetStroke(picthree);
break;
case 1:
setStroke(pictwo);
resetStroke(picone);
resetStroke(picthree);
break;
case 2:
setStroke(picthree);
resetStroke(pictwo);
resetStroke(picone);
break;
default:
break;
}
imag_index++;
if (imag_index == images.length) ;
{
imag_index = 0;
}
try {
String imagpath = getClass().getResource(images[imag_index]).toURI().toString();
Image img = new Image(imagpath);
imageslidder.setImage(img);
} catch (Exception e) {
}
}
void prevImage() {
nextImage();
}
void setStroke(Circle indicator) {
indicator.setFill(Paint.valueOf("#03a9f4"));
indicator.setStroke(Paint.valueOf("#cddc39"));
indicator.setStrokeType(StrokeType.OUTSIDE);
indicator.setStrokeWidth(5);
}
void resetStroke(Circle indicator) {
indicator.setFill(Paint.valueOf("ffffff"));
indicator.setStroke(Paint.valueOf("#1e90ff"));
indicator.setStrokeType(StrokeType.INSIDE);
indicator.setStrokeWidth(1);
}
public void initializer(URL url, ResourceBundle rb)
{
}
}

JavaFX WebView blocks GUI

All it's ok when i open light weight's pages but when i wan't to open some bigger the GUI blocks and not responding until the site load's. I try to give it to background thread but it's not working.
MainWindowController:
WebControl webcontroller = new WebControl();
DatabaseControl datacontroller;
#FXML
private ToggleButton PowypadkoweBt;
#FXML
private ToggleButton UszkodzoneBt;
#FXML
private ToggleButton MailBt;
#FXML
private ToggleButton SMSBt;
#FXML
private Button SendBt;
#FXML
private ScrollPane WynikiScroll;
#FXML
private TableView DoneTable;
#FXML
private TableColumn CheckCol, OpisCol, LoginCol;
#FXML
private TextArea MessageArea;
#FXML
private WebView WebControl;
#FXML
private Button NEXT;
#FXML
private Button PREVIOUS;
#FXML
private Label PAGE;
#Override
public void initialize(URL url, ResourceBundle rb) {
this.CheckCol.setCellValueFactory(
new Callback<CellDataFeatures<UsedTableRow, Boolean>, ObservableValue<Boolean>>() {
#Override
public ObservableValue<Boolean> call(CellDataFeatures<UsedTableRow, Boolean> param) {
return param.getValue().getCheckedProperty();
}
});
this.CheckCol.setCellFactory(CheckBoxTableCell.forTableColumn(this.CheckCol));
this.CheckCol.setEditable(false);
this.CheckCol.setMinWidth(50);
this.CheckCol.setMaxWidth(50);
this.OpisCol.setCellValueFactory(new PropertyValueFactory<UsedTableRow, String>("Description"));
this.LoginCol.setCellValueFactory(new PropertyValueFactory<UsedTableRow, String>("Login"));
ObservableList<UsedTableRow> data = FXCollections.observableArrayList();
try {
datacontroller = new DatabaseControl();
data.addAll(datacontroller.getRowsFromEntity());
} catch (ClassNotFoundException ex) {
Alert alert = new Alert(AlertType.WARNING);
alert.setContentText("Nie udało się nawiązać połączenia z bazą danych. Błąd klasy.");
alert.setHeaderText("Błąd klasy.");
alert.setTitle("Błąd");
alert.show();
} catch (SQLException ex) {
Alert alert = new Alert(AlertType.WARNING);
alert.setHeaderText("Błąd SQL.");
alert.setContentText("Nie udało się nawiązać połączenia z bazą danych. Błąd SQL.");
alert.setTitle("Błąd");
alert.show();
}
this.DoneTable.setItems(data);
this.WebControl.getEngine().load("http://otomoto.pl");
this.PAGE.setText((this.webcontroller.getIteratorAuctions() + this.webcontroller.getIteratorItems() - 10) + " z " + this.webcontroller.getItemsIds().size());
// loadNewSite();
this.WebControl.autosize();
this.WebControl.widthProperty().addListener(new ChangeListener<Object>() {
public void changed(ObservableValue<?> observable, Object oldValue, Object newValue) {
Double width = (Double) newValue;
WebControl.setPrefWidth(width);
WebControl.autosize();
}
});
this.WebControl.requestLayout();
this.WebControl.setContextMenuEnabled(false);
this.WebControl.getEngine().setJavaScriptEnabled(true);
this.WebControl.getEngine().setUserAgent("Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.117 Safari/537.36");
this.PowypadkoweBt.setSelected(true);
this.UszkodzoneBt.setSelected(true);
}
#FXML
private void PowypadkoweAction(ActionEvent event) {
if (this.PowypadkoweBt.isSelected()) {
this.webcontroller.refresh(true);
} else {
this.webcontroller.refresh(false);
}
loadNewSite();
}
#FXML
private void UszkodzoneAction(ActionEvent event) {
}
#FXML
private void SMSAction(ActionEvent event) {
}
#FXML
private void MailAction(ActionEvent event) {
}
#FXML
private void SendAction(ActionEvent event) {
}
#FXML
private void PREVIOUSAction(ActionEvent event) {
webcontroller.previousAuction();
loadNewSite();
}
#FXML
private void NEXTAction(ActionEvent event) {
webcontroller.nextAuction();
loadNewSite();
this.WebControl.autosize();
}
private void updateDoneTable() {
ObservableList<UsedTableRow> data = FXCollections.observableArrayList();
data.addAll(datacontroller.getRowsFromEntity());
this.DoneTable.getItems().clear();
this.DoneTable.setItems(data);
}
private void loadNewSite() {
Service<Void> service = new Service<Void>() {
#Override
protected Task<Void> createTask() {
return new Task<Void>() {
#Override
protected Void call() throws Exception {
//Background work
final CountDownLatch latch = new CountDownLatch(1);
Platform.runLater(new Runnable() {
#Override
public void run() {
try {
WebControl.getEngine().load(webcontroller.getSelectedURL());
PAGE.setText((webcontroller.getIteratorAuctions() + webcontroller.getIteratorItems() - 10) + " z " + webcontroller.getItemsIds().size());
} finally {
latch.countDown();
}
}
});
latch.await();
//Keep with the background work
return null;
}
};
}
};
service.start();
/* Task task = new Task(new Runnable() {
#Override
public void run() {
WebControl.getEngine().load(webcontroler.getSelectedURL());
}
});
tr.run();
this.PAGE.setText((this.webcontroler.getIteratorAuctions() + this.webcontroler.getIteratorItems() - 10) + " z " + this.webcontroler.getItemsIds().size());
*/
}}
CInsurance Application class :
#Override
public void start(Stage primaryStage) {
try {
Parent root = FXMLLoader.load(getClass().getResource("/cinsurance/MainWindow.fxml"));
Scene scene = new Scene(root);
scene.getStylesheets().add(getClass().getResource("/cinsurance/mainwindow.css").toExternalForm());
primaryStage.setTitle("Aplikacja Ubezpieczeniowa CInsurance");
primaryStage.setScene(scene);
primaryStage.show();
} catch (IOException ex) {
Logger.getLogger(CInsurance.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}}
Thanks for any help.
After i lost a lot of time on thinking why , i just continue to code modules for this application and i add some multithreading into initialize method of controller and ... it was very strange . Everything is working ok , even when i'm loading heavy page's. I still don't know why multithreading unlocks the blockade... but it can be also the change of JDK because i must change it to 32 bit form 64 bit. After all it is strange.

Javafx Task - update progress from a method

In a JavaFX application I wish to update a status bar according to some work logic which I've implemented in an other class.
I can't figure out how to combine my desire to pass to work logic to the method (and not to write it inside the task) and to know about the work progress percentage.
This is an example of the controller with the Task:
public class FXMLDocumentController implements Initializable {
#FXML private Label label;
#FXML ProgressBar progressBar;
#FXML
private void handleButtonAction(ActionEvent event) {
Service<Void> myService = new Service<Void>() {
#Override
protected Task<Void> createTask() {
return new Task<Void>() {
#Override
protected Void call() throws Exception {
try {
DatabaseFunctionality.performWorkOnDb();
//updateProgress(1, 1);
} catch (InterruptedException ex) {
Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
};
}
};
progressBar.progressProperty().bind(myService.progressProperty());
myService.restart();
}
#Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
}
}
This is the helper class:
public class DatabaseFunctionality {
public static void performWorkOnDb () throws InterruptedException {
for (int i = 1; i <= 100; i++) {
System.out.println("i=" + i);
Thread.sleep(100);
//Update progress
}
}
}
Thank you
You have a couple of options here. One is to do as Uluk suggests and expose an observable property in your DatabaseFunctionality class:
public class DatabaseFunctionality {
private final ReadOnlyDoubleWrapper progress = new ReadOnlyDoubleWrapper();
public double getProgress() {
return progressProperty().get();
}
public ReadOnlyDoubleProperty progressProperty() {
return progress ;
}
public void performWorkOnDb() throws Exception {
for (int i = 1; i <= 100; i++) {
System.out.println("i=" + i);
Thread.sleep(100);
progress.set(1.0*i / 100);
}
}
}
And now in your Task, you can observe that property and update the task's progress:
Service<Void> myService = new Service<Void>() {
#Override
protected Task<Void> createTask() {
return new Task<Void>() {
#Override
protected Void call() throws Exception {
try {
DatabaseFunctionality dbFunc = new DatabaseFunctionality();
dbFunc.progressProperty().addListener((obs, oldProgress, newProgress) ->
updateProgress(newProgress.doubleValue(), 1));
dbaseFunc.performWorkOnDb();
} catch (InterruptedException ex) {
Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
};
}
};
Another option (in case you don't want your data access object to depend on the JavaFX properties API) is to pass the data access object a callback to update the progress. A BiConsumer<Integer, Integer> would work for this:
public class DatabaseFunctionality {
private BiConsumer<Integer, Integer> progressUpdate ;
public void setProgressUpdate(BiConsumer<Integer, Integer> progressUpdate) {
this.progressUpdate = progressUpdate ;
}
public void performWorkOnDb() throws Exception {
for (int i = 1; i <= 100; i++) {
System.out.println("i=" + i);
Thread.sleep(100);
if (progressUpdate != null) {
progressUpdate.accept(i, 100);
}
}
}
}
and then
Service<Void> myService = new Service<Void>() {
#Override
protected Task<Void> createTask() {
return new Task<Void>() {
#Override
protected Void call() throws Exception {
try {
DatabaseFunctionality dbFunc = new DatabaseFunctionality();
dbFunc.setProgressUpdate((workDone, totalWork) ->
updateProgress(workDone, totalWork));
dbaseFunc.performWorkOnDb();
} catch (InterruptedException ex) {
Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
};
}
};
public void initialize() {
Task<Void> task = new Task<>() {
#Override
protected Void call() {
try {
Double d = 0.0;
for (int i = 1; i <= 100; i++) {
Thread.sleep(100);
d = 1.0 * i / 100;
updateProgress(d, 1);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
};
task.progressProperty().addListener((obs, oldProgress, newProgress) -> {
System.out.println((newProgress.doubleValue() * 100) + "% completed");
});
new Thread(task).start();
}

how to terminate a javafx.concurrent.Service in javafx 8

Hi this is the structure of my application.
MCVE:
#FXML
void OnSimulateClick(ActionEvent event) throws IOException {
if (event.getSource() == simulatebutton) {
primaryStage = (Stage) simulatebutton.getScene().getWindow();
pane = (Pane) FXMLLoader.load(TDC.class.getResource("view/Simulation.fxml"));
scene = new Scene(pane);
primaryStage.setScene(scene);
primaryStage.show();
}
}
FXML
<Pane prefHeight="500.0" prefWidth="750.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.mdw.tdc.view.SimulationController" >
<children>
<Button fx:id="abortbutton" layoutX="650.0" layoutY="230.0" onAction="#onAbortClicked" text="Abort" />
<Button fx:id="homebutton" layoutX="650.0" layoutY="330.0"onAction="#onHomeClicked" text="Home" />
<TextArea fx:id="logscreen" layoutX="21.0" layoutY="20.0" prefHeight="395.0" prefWidth="600.0" />
</children>
</Pane>
controller
public class SimulationController implements Initializable {
#FXML
private Button homebutton;
#FXML
private TextArea logscreen;
#FXML
private Button abortbutton;
private Simulate simulate;
#Override
public void initialize(URL location, ResourceBundle resources) {
simulate = new Simulate(list, logscreen);
simulate.setOnCancelled(new EventHandler<WorkerStateEvent>() {
#Override
public void handle(WorkerStateEvent event) {
System.out.println("Simulation Aborted by User...");
}
});
simulate.setOnFailed(new EventHandler<WorkerStateEvent>() {
#Override
public void handle(WorkerStateEvent event) {
System.out.println("Simulation Failed...");
}
});
simulate.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
#Override
public void handle(WorkerStateEvent event) {
System.out.println("Simulation Success...");
}
});
simulate.start();
}
#FXML
void onAbortClicked(ActionEvent event) throws IOException,
InterruptedException {
if (event.getSource() == abortbutton) {
simulate.cancel();
}
}
}
#FXML
void onHomeClicked(ActionEvent event) throws IOException {
if (event.getSource() == homebutton) {
simulate.reset();
/*back to Home screen*/
pane = (Pane) FXMLLoader.load(TDC.class.getResource("view/Simulation.fxml"));
scene = new Scene(pane);
primaryStage.setScene(scene);
primaryStage.show();
}
}
Simulate Sercice
public class Simulate extends Service<Void> {
private ObservableList<TestData> list;
private TextArea logscreen;
private ConsoleStream consoleStream;
public Simulate(ObservableList<TestData> list, TextArea logscreen) {
this.list = list;
this.logscreen = logscreen;
}
#Override
protected Task<Void> createTask() {
return new Task<Void>() {
#Override
protected Void call() throws Exception {
consoleStream = new ConsoleStream(logscreen);
consoleStream.start();
/*Some Code*/
System.out.println("End of Simulation");
return null;
}
};
}
/* Few other methods called from inside my code inside createTask()>call() method */
// using this method to flag when cancelled
public void isFlagged(boolean b) {
consoleStream.isFlagged(true);
consoleStream.setOnCancelled(new EventHandler<WorkerStateEvent>() {
#Override
public void handle(WorkerStateEvent event) {
consoleStream.reset();
}
});
consoleStream.cancel();
}
}
ConsoleStream Service
public class ConsoleStream extends Service<Void> {
private PipedOutputStream outPipedOutputStream, errorPipedOutputStream;
private PipedInputStream outPipedInputStream, errorPipedInputStream;
private TextArea logscreen;
private Console outCon;
public ConsoleStream(TextArea logscreen) {
this.logscreen = logscreen;
}
#Override
protected Task<Void> createTask() {
return new Task<Void>() {
#Override
protected Void call() throws Exception {
try {
System.err.flush();
System.out.flush();
outPipedInputStream = new PipedInputStream();
outPipedOutputStream = new PipedOutputStream(
outPipedInputStream);
System.setOut(new PrintStream(outPipedOutputStream));
errorPipedInputStream = new PipedInputStream();
errorPipedOutputStream = new PipedOutputStream(
errorPipedInputStream);
System.setErr(new PrintStream(errorPipedOutputStream));
outCon = new Console(outPipedInputStream, logscreen);
outCon.setOnCancelled(new EventHandler<WorkerStateEvent>() {
#Override
public void handle(WorkerStateEvent event) {
// TODO Auto-generated method stub
System.out.println("ConsoleStream Aborted by User...");
outCon.reset();
}
});
outCon.start();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
};
}
public void isFlagged(boolean b) {
outCon.cancel();
}
}
Console Service
public class Console extends Service<Void> {
private final InputStream inputStream;
private TextArea logscreen;
public Console(PipedInputStream errorPipedInputStream, TextArea logscreen) {
inputStream = errorPipedInputStream;
this.logscreen = logscreen;
}
#Override
protected Task<Void> createTask() {
return new Task<Void>() {
#Override
protected Void call() throws Exception {
while(isCancelled()){
inputStream.close();
break;
}
try {
InputStreamReader is = new InputStreamReader(inputStream);
BufferedReader br = new BufferedReader(is);
while (br.readLine() != null) {
String read = br.readLine();
logscreen.appendText(read + "\n");
}
is.close();
br.close();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
};
}
}
This is the first attempt at JavaFx not sure this is good way of doing. any suggestions are appriciated
Thanks

Resources