I'm working on an application feature to show the progress status in TextArea. And I'm using observer pattern to implement that. But when I try to append the status information to the TextArea, the Window freezes. How to solve that problem?
The freeze window like this :
When doSomething() is done. The freezes window back to normal. Like this:
Here are my codes
start(Stage stage)
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("view/progressStatus.fxml"));
Parent root = loader.load();
statusStage = new Stage();
statusScene = new Scene(root);
statusStage.setScene(statusScene);
progressStatusController = loader.getController();
statusStage.show();
MyFiles myFiles = new MyFiles();
myFiles.addObserver(progressStatusController);
newMyFiles.doSomething();
public class ProgressStatusController implements Initializable, Observer {
#FXML private ProgressBar progressBar;
#FXML private TextArea textArea;
private String[] message;
#Override
public void initialize(URL location, ResourceBundle resources) {
}
#Override
public void update(Observable o, Object arg) {
System.out.println(arg);
textArea.textProperty().set(textArea.getText().concat("\n").concat((String)arg));
textArea.positionCaret(textArea.getText().length());
}
}
doSomething is a long-running task and therefore should not be run on the JavaFX application thread. However the start method is run on this thread.
You need to run doSomething on a different thread to avoid blocking the application thread. Updates to the UI should be done on the application thread; therefore you should use Platform.runLater to execute the updates:
...
MyFiles myFiles = new MyFiles();
myFiles.addObserver(progressStatusController);
new Thread(newMyFiles::doSomething).start();
#Override
public void update(Observable o, Object arg) {
System.out.println(arg);
Platform.runLater(() -> {
textArea.setText(textArea.getText() + "\n" + arg);
textArea.positionCaret(textArea.getText().length());
});
}
🔗In addition to Fabian's answer i recommend you to use JavaFX Service.Service is running into a different than JavaFX Thread and you can do what you want there but be careful modifying JavaFX Nodes that are into the SceneGraph is not allowed so you have to use:
Platform.runLater(() -> {
//your code...
});
Typical example of Service for reading the files into a folder using
Files.walk(..) method + Streams:
/**
* With this Service you can count the files of a folder
* it is a minimalistic example of the power of Services
*
*/
public class ServiceExample extends Service<Void> {
/**
* Constructor
*/
public InputService() {
setOnSucceeded(s ->{
//code
});
setOnCancelled(c ->{
//code
});
setOnFailed(c ->{
//code
});
}
#Override
protected Task<Void> createTask() {
return new Task<Void>() {
#Override
protected Void call() throws Exception {
countFiles(new File("the path of the folder");
return null;
}
/**
* Count files in a directory (including files in all sub
* directories)
*
* #param directory
* the directory to start in
* #return the total number of files
*/
private int countFiles(File dir) {
if (dir.exists())
try (Stream<Path> paths = Files.walk(Paths.get(dir.getPath()))) {
return (int) paths.filter(s -> { //where s is a File or Folder
// System.out.println("Counting..." +
// s.toString())
// cancelled?
if (isCancelled())
paths.close();
else
System.out.println(s);
return false;
}).count();
} catch (IOException ex) {
Main.logger.log(Level.WARNING, "", ex);
}
return 0;
}
};
}
}
Related
I have this javafx controller method trying to open up a local html file that's generated by the application. The function is running in another thread.
My main class that starts the application, using fxmlloader:
#SpringBootApplication
public class DemoAppiumProjectApplication extends Application
{
public static ConfigurableApplicationContext applicationContext;
public static void main(String[] args)
{
applicationContext = SpringApplication.run(DemoAppiumProjectApplication.class, args);
Application.launch(DemoAppiumProjectApplication.class, args);
}
#Override
public void start(Stage stage)
throws Exception
{
stage.setTitle("JS SDK Demo Test Suite");
stage.setScene(new Scene(createRoot()));
stage.show();
}
private Parent createRoot()
throws IOException
{
FXMLLoader fxmlLoader = new FXMLLoader();
fxmlLoader.setLocation(DemoAppiumProjectApplication.class.getResource("/setup.fxml"));
fxmlLoader.setControllerFactory(applicationContext::getBean);
return fxmlLoader.load();
}
}
My controller class:
#Override
public void initialize(URL url, ResourceBundle resourceBundle)
{
Task<String> task = new Task<String>()
{
#Override
protected String call()
throws Exception
{
showFinalDialog();
return null;
}
};
new Thread(task).start();
}
public void showFinalDialog()
{
Platform.runLater(() -> {
String text = "Test is complete! Click to view test report.";
Alert alert = new Alert(Alert.AlertType.INFORMATION, text, ButtonType.OK);
alert.getDialogPane().setMinHeight(Region.USE_PREF_SIZE);
Optional<ButtonType> buttonType = alert.showAndWait();
if (!buttonType.isPresent())
{
Platform.exit();
}
else if (buttonType.get() == ButtonType.OK)
{
if (Desktop.isDesktopSupported())
{
try
{
Desktop.getDesktop()
.open(new File(System.getProperty("user.dir") + "/test-output/ExtentReport.html"));
}
catch (IOException e)
{
createAlertWindow(e.getMessage());
}
}
Platform.exit();
}
});
}
Now the only question is the condition Desktop.isDesktopSupported return false here. I wrote another main function in another project to test again, it returns true.
I guess that means Desktop is supported on my OS (windows 10), but not supported in my javafx application?
So what am I missing here?
And perhaps there's another recommanded way to open up this html file as well? Any ideas would help! Thanks!
Why use the Desktop to open a local html file when you are using javafx already.
Here is an example.
public class HelpWindow extends Application{
#Override
public void start(Stage primaryStage) throws Exception{
FlowPane root = new FlowPane();
primaryStage.setTitle("Help Window");
WebView view = new WebView();
WebEngine engine = view.getEngine();
engine.load( HelpWindow.class.getResource("help.html").toString());
root.getChildren().add(view);
Scene scene = new Scene(root, 790, 675);
primaryStage.setScene(scene);
primaryStage.show();
System.out.println(Desktop.isDesktopSupported());
}
}
That will show the help.html file, that I have included as a resource. From the looks of it, you might be generating your .html file so you would have to get the file a different way.
<html>
<body>
<p> Here is some text</p>
original question
</body>
</html>
I've also included printing out the Desktop.isDesktopSupported() since that returns true for me.
I suspect one issue you are having is that Desktop.getDesktop().open() is non-blocking, so your application just quits before your desktop can actually open the webpage.
I'm using a recursive method which implements the use of the SwingWorker class to do a research in one folder and all its subfolders - in the local hard drive.
Basically works fine but I'm stuck when I want to stop the SwingWorker method: when the user change the 'source folder' (I'm using a JTree - JAVAFX - to show all the folders in the local hard drive), I want to stop the current 'SwingWorker research' in that folder and start a new one, with the newest 'source path' results choosed from the user.
All the results of the research are stored in a private ObservableList - and updated everytime in the done() method, just by filling one TableView - JavaFX: so, when the user change the 'source path' I have to clean the results of the previous research.
Start method:
private static ObservableList<msg> data = FXCollections.observableArrayList();
private static SwingWorker<Void, Void> worker;
private static String currentFolder;
#Override
public void start(Stage primaryStage) throws Exception {
// TODO Auto-generated method stub
stage = primaryStage;
primaryStage.setScene(new Scene(createContent()));
styleControls();
primaryStage.initStyle(StageStyle.UNDECORATED);
primaryStage.setMaximized(true);
primaryStage.setFullScreen(false);
primaryStage.show();
msgp = new MsgParser();
}
createContent() method- recursive function its called here:
public Parent createContent() {
tree.getSelectionModel().selectedItemProperty().addListener( new ChangeListener<Object>() {
#Override
public void changed(ObservableValue observable, Object oldValue,
Object newValue) {
TreeItem<File> selectedItem = (TreeItem<File>) newValue;
currentFolder = selectedItem.getValue().getAbsolutePath();
// I want to stop here the previous SwingWorker call : the tree
// ChangeListener event is called when the user change the
// source folder of the research, by selecting one TreeItem on it.
if(worker!= null)
worker.cancel(true);
//Here I clean previous results
data.clear();
TV.setItems(data);
//And I call again the method with the new source Folder
ListMail(new File(currentFolder));
}
});
}
ListMail() method: [recursive SwingWorker]
private void ListMail(File dir) {
worker = new SwingWorker<Void, Void>() {
#Override
protected Void doInBackground() throws Exception {
File[] directoryListing = dir.listFiles();
if (directoryListing != null) {
for (File child : directoryListing) {
if(!worker.isCancelled()) {
if(child != null){
if(!child.isDirectory()) {
if(child.getAbsolutePath().substring(child.getAbsolutePath().lastIndexOf('.')+1).equals("msg")) {
Message message = msgp.parseMsg(child.getPath());
String percorsoMail = child.getAbsolutePath().toUpperCase();
if(message != null) {
String fromEmail = message.getFromEmail();
String fromName = message.getFromName();
String subject = message.getSubject();
String received = message.getDate().toString();
String name;
if(fromEmail != null)
name = fromName + "(" + fromEmail + ")";
else name = fromName;
msg Message = new msg(name, subject, received);
if(!data.contains(Message))
data.add(Message);
//I use the Platform.runLater to
// take count of the number of results found
//It updates the GUI - works fine
Platform.runLater(new Runnable() {
#Override public void run() {
if(data != null && data.size() > 0)
setStatusLabel(data.size());
else
setStatusLabel(0);
}
});
}
}
} else {
/**
* Recursive call here : I do the research
* for the subfolders
*/
ListMail(child);
}
} else {
}
}
}
}
return null;
}
// Update GUI Here
protected void done() {
// I refresh here the TableView: works fine on-the-fly added results
TableView.setItems(data);
TableView.refresh();
}
};
//This doesn't do anything
if(!worker.isCancelled())
worker.execute();
}
Basically, the issue is that the SwingWorker thread never stop, I'm thinking because of the recursive calls which creates new pid process at every run or something ?
Also by using a dedicated external button, which I prefer to avoid, gives no results:
refreshBtn.setOnAction(e -> {
//Handle clicks on refreshBtn button
worker.cancel(true);
});
After I click on TreeItem to change source-folder, it just delete all the ObservableList elements created at that moment, but the previous research don't stop.
Everything works fine instead if I wait the research its finished - but this can works only when I'm in a deep-level folder, while I can't obviously wait when the research start with the "C:\" folder.
Ok so that's here how I managed this by using javafx.concurrent.
Just to point my experience with this, it seems using a recursive background Task for potentially long computations, such as scanning the Whole local drive like in my example, it's very memory consuming - also because I stored some results of this background computation in static local variables to access them faster: the result was a data-structure (ObservableList) with over 5000+ instances of a custom class to represent that specific data computed and then the OutOfMemoryError message or the background thread just going like in 'stand-by' without any advice after running for long time (waiting for garbage collection?).
Anyway here's the code that sum up how I solved: the threads are correctly closed. By the way, sometimes, there's a little 'GUI delay' due to cleaning the GUI on the isCancelled() method check: the GUI swing between clear/not clear, because in my opinion it keeps get filled by the results of the previous tasks in the recursion.
private static BackgroundTask backgroundTask;
private static Thread thread;
tree.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<Object>() {
#Override
public void changed(final ObservableValue observable, final Object oldValue, final Object newValue) {
//I close previous running background tasks if there's any
if (backgroundTask != null) {
while (backgroundTask.isRunning()) {
backgroundTask.cancel(true);
// reset GUI nodes here used to show results of the previous thread
}
}
backgroundTask = new BackGoundTask();
thread= new Thread(backgroundTask);
thread.setDaemon(true);
thread.start();
//This will be called only when latest recursion is finished, not at every run
backgroundTask.setOnSucceeded(e -> {});
}
});
BackgroundTask class:
public static class BackgroundTask extends Task<Object> {
// .. variables used by the task here
//constructor: initialize variables at every run of the Task
public BackgroundTask() {
}
#Override
protected Object call() throws Exception {
if (!isCancelled()) {
// ... Do all background work here
Platform.runLater(new Runnable() {
#Override
public void run() {
// GUI progress can goes here
}
});
//recursion here
if(something) {
//...
} else {
call();
}
} else {
//user want to cancel task: clean GUI nodes
}
return null;
}
}
I have written a piece of code for downloading a file from internet (in background service) and showing the progress of download in a popup stage. The code compiles successfully and there is no runtime error. However no download takes place and progress indicator remains indeterminate.
The code is tailored for illustrating my point. Please have a look at it and let me understand where I have gone wrong.
Thanks!
public class ExampleService extends Application {
URL url;
Stage stage;
public void start(Stage stage)
{
this.stage = stage;
stage.setTitle("Hello World!");
stage.setScene(new Scene(new StackPane(addButton()), 400, 200));
stage.show();
}
private Button addButton()
{
Button downloadButton = new Button("Download");
downloadButton.setOnAction(new EventHandler<ActionEvent>()
{
public void handle(ActionEvent e)
{
FileChooser fileSaver = new FileChooser();
fileSaver.getExtensionFilters().add(new FileChooser.ExtensionFilter("PDF", "pdf"));
File file = fileSaver.showSaveDialog(stage);
getDownloadService(file).start();
}
});
return downloadButton;
}
private Service getDownloadService(File file)
{
Service downloadService = new Service()
{
protected Task createTask()
{
return doDownload(file);
}
};
return downloadService;
}
private Task doDownload(File file)
{
Task downloadTask = new Task<Void>()
{
protected Void call() throws Exception
{
url = new URL("http://www.daoudisamir.com/references/vs_ebooks/html5_css3.pdf");
// I have used this url for this context only
org.apache.commons.io.FileUtils.copyURLToFile(url, file);
return null;
}
};
showPopup(downloadTask);
return downloadTask;
}
Popup showPopup(Task downloadTask)
{
ProgressIndicator progressIndicator = new ProgressIndicator();
progressIndicator.progressProperty().bind(downloadTask.progressProperty());
Popup progressPop = new Popup();
progressPop.getContent().add(progressIndicator);
progressPop.show(stage);
return progressPop;
// I have left out function to remove popup for simplicity
}
public static void main(String[] args)
{
launch(args);
}}
The line:
org.apache.commons.io.FileUtils.copyURLToFile(url, file);
...doesn't provide you any information about the progress of your download (there is no callback or any other indication of its progress). It just downloads something without giving you feedback.
You will have to use something else that gives you feedback on the progress.
Take a look at this questions answers for solutions with feedback (it is for Swing, but you should be able to adapt them for JavaFX): Java getting download progress
You bind the ProgressIndicator's progress property to the Task's progress property, so that changes in the latter will be reflected in the former. However you never actually update your Task's progress.
If you want the progress indicator to show something, you're going to have to call updateProgress(workDone, max) within your task's body (or elsewhere). And that might be tricky if the download logic you're using doesn't give you any progress callbacks. (You could, perhaps, spawn a thread to repeatedly check the size of the file on the filesystem and use that as your current workDone; but you'd need to know what the eventual/complete size of the file would be in order to turn this into a percentage, which may or may not be easy.)
How can I safely update the widgets on a JavaFX GUI from within a JavaFX Service. I remember when I was developing with Swing, I used to 'invoke later' and other various swing worker utilities to ensure that all updates to the UI were handled safely in the Java Event Thread. Here is an example of a simple service thread that handles datagram messages. The bit that is missing is where the datagram message is parsed and corresponding UI widgets are updated. As you can see the service class is very simplistic.
I'm not sure if I need to use simple binding properties (like message) or alternatively should I should pass widgets to the constructor of my StatusListenerService (which is probably not the best thing to do). Can someone give me a good similar example that I would work from.
public class StatusListenerService extends Service<Void> {
private final int mPortNum;
/**
*
* #param aPortNum server listen port for inbound status messages
*/
public StatusListenerService(final int aPortNum) {
this.mPortNum = aPortNum;
}
#Override
protected Task<Void> createTask() {
return new Task<Void>() {
#Override
protected Void call() throws Exception {
updateMessage("Running...");
try {
DatagramSocket serverSocket = new DatagramSocket(mPortNum);
// allocate space for received datagrams
byte[] bytes = new byte[512];
//message.setByteBuffer(ByteBuffer.wrap(bytes), 0);
DatagramPacket packet = new DatagramPacket(bytes, bytes.length);
while (!isCancelled()) {
serverSocket.receive(packet);
SystemStatusMessage message = new SystemStatusMessage();
message.setByteBuffer(ByteBuffer.wrap(bytes), 0);
}
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
updateMessage("Cancelled");
return null;
}
};
}
}
The "low-level" approach is to use Platform.runLater(Runnable r) to update the UI. This will execute r on the FX Application Thread, and is the equivalent of Swing's SwingUtilities.invokeLater(...). So one approach is simply to call Platform.runLater(...) from inside your call() method and update the UI. As you point out, though, this essentially requires the service knowing details of the UI, which is undesirable (though there are patterns that work around this).
Task defines some properties and has corresponding updateXXX methods, such as the updateMessage(...) method you call in your example code. These methods are safe to call from any thread, and result in an update to the corresponding property to be executed on the FX Application Thread. (So, in your example, you can safely bind the text of a label to the messageProperty of the service.) As well as ensuring the updates are performed on the correct thread, these updateXXX methods also throttle the updates, so that you can essentially call them as often as you like without flooding the FX Application Thread with too many events to process: updates that occur within a single frame of the UI will be coalesced so that only the last such update (within a given frame) is visible.
You could leverage this to update the valueProperty of the task/service, if it is appropriate for your use case. So if you have some (preferably immutable) class that represents the result of parsing the packet (let's call it PacketData; but maybe it is as simple as a String), you make
public class StatusListener implements Service<PacketData> {
// ...
#Override
protected Task<PacketData> createTask() {
return new Task<PacketData>() {
// ...
#Override
public PacketData call() {
// ...
while (! isCancelled()) {
// receive packet, parse data, and wrap results:
PacketData data = new PacketData(...);
updateValue(data);
}
return null ;
}
};
}
}
Now you can do
StatusListener listener = new StatusListener();
listener.valueProperty().addListener((obs, oldValue, newValue) -> {
// update UI with newValue...
});
listener.start();
Note that the value is updated to null by the code when the service is cancelled, so with the implementation I outlined you need to make sure that your listener on the valueProperty() handles this case.
Also note that this will coalesce consecutive calls to updateValue() if they occur within the same frame rendering. So this is not an appropriate approach if you need to be sure to process every data in your handler (though typically such functionality would not need to be performed on the FX Application Thread anyway). This is a good approach if your UI is only going to need to show the "most recent state" of the background process.
SSCCE showing this technique:
import java.util.Random;
import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.concurrent.Service;
import javafx.concurrent.Task;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class LongRunningTaskExample extends Application {
#Override
public void start(Stage primaryStage) {
CheckBox enabled = new CheckBox("Enabled");
enabled.setDisable(true);
CheckBox activated = new CheckBox("Activated");
activated.setDisable(true);
Label name = new Label();
Label value = new Label();
Label serviceStatus = new Label();
StatusService service = new StatusService();
serviceStatus.textProperty().bind(service.messageProperty());
service.valueProperty().addListener((obs, oldValue, newValue) -> {
if (newValue == null) {
enabled.setSelected(false);
activated.setSelected(false);
name.setText("");
value.setText("");
} else {
enabled.setSelected(newValue.isEnabled());
activated.setSelected(newValue.isActivated());
name.setText(newValue.getName());
value.setText("Value: "+newValue.getValue());
}
});
Button startStop = new Button();
startStop.textProperty().bind(Bindings
.when(service.runningProperty())
.then("Stop")
.otherwise("Start"));
startStop.setOnAction(e -> {
if (service.isRunning()) {
service.cancel() ;
} else {
service.restart();
}
});
VBox root = new VBox(5, serviceStatus, name, value, enabled, activated, startStop);
root.setAlignment(Pos.CENTER);
Scene scene = new Scene(root, 400, 400);
primaryStage.setScene(scene);
primaryStage.show();
}
private static class StatusService extends Service<Status> {
#Override
protected Task<Status> createTask() {
return new Task<Status>() {
#Override
protected Status call() throws Exception {
Random rng = new Random();
updateMessage("Running");
while (! isCancelled()) {
// mimic sporadic data feed:
try {
Thread.sleep(rng.nextInt(2000));
} catch (InterruptedException exc) {
Thread.currentThread().interrupt();
if (isCancelled()) {
break ;
}
}
Status status = new Status("Status "+rng.nextInt(100),
rng.nextInt(100), rng.nextBoolean(), rng.nextBoolean());
updateValue(status);
}
updateMessage("Cancelled");
return null ;
}
};
}
}
private static class Status {
private final boolean enabled ;
private final boolean activated ;
private final String name ;
private final int value ;
public Status(String name, int value, boolean enabled, boolean activated) {
this.name = name ;
this.value = value ;
this.enabled = enabled ;
this.activated = activated ;
}
public boolean isEnabled() {
return enabled;
}
public boolean isActivated() {
return activated;
}
public String getName() {
return name;
}
public int getValue() {
return value;
}
}
public static void main(String[] args) {
launch(args);
}
}
I have a javafx program which I want to use to analyze a website. For the start I just want to print the sourcecode of a site into a TextArea, but before that, I write "loading website sourcecode..."
My target is to write "loading website sourcecode..." first, and then after some seconds when the parsing of the site is finished, add that sourcecode.
At the Moment when I press the button, nothing happens and after 3-5 seconds the "loading website sourcecode..." message and the sourcecode is displayed at once.
So I actually want to show strings one after another. I already googled for 2 hours and tried things with threads, invokelater, platform.runLater() and so on but nothing worked, the code is simple.
ModelView.java - Controller Class
package root;
import javafx.application.Platform;
...
public class ModelView {
#FXML public TextField UrlInput;
// This gets called when the button is pressed
public void checkUrl() throws InterruptedException
{
String url = UrlInput.getText();
LogWriter lw = new LogWriter();
lw.printMsg("loading website sourcecode...");
lw.printMsg(HTMLParser.directUrlToCode(url));
}
}
LogWriter.java
package root;
import javafx.beans.value.ObservableValue;
...
public class LogWriter extends Thread{
#FXML TextArea Log;
public LogWriter()
{
Log = (TextArea) Main.scene.lookup("#Log");
}
void printMsg(String s)
{
Log.setText(this.Log.getText()+"\n"+s);
}
}
EDIT:
There is not much to say about the HTMLParser methods, but I add that it extends Thread.
I tried changing ModelView.java to that:
ModelView.java - version 2
package root;
import javafx.application.Platform;
...
public class ModelView<V> {
#FXML public TextField UrlInput;
// This gets called when the button is pressed
public void checkUrl() throws InterruptedException
{
String url = UrlInput.getText();
LogWriter lw0 = new LogWriter();
lw0.start();
lw0.printMsg("loading website sourcecode...");
HTMLParser hp = new HTMLParser();
hp.start();
LogWriter lw1 = new LogWriter();
lw1.start();
lw1.printMsg(hp.directUrlToCode(url));
}
}
Still the same effect.
EDIT2:
This is another version I tried, in this case, "loading website sourcecode..." is not even displaying, I am going on with my tries...
ModelView.java checkUrl() - Version 3
public void checkUrl() throws InterruptedException
{
String url = UrlInput.getText();
Task<Void> task = new Task<Void>(){
#Override protected Void call() throws Exception {
if(isCancelled()) {
updateMessage("Cancelled");
LogWriter lw = new LogWriter();
lw.printMsg("loading website sourcecode...");
}
return null;
}
};
Thread t = new Thread(task);
t.start();
HTMLParser hp = new HTMLParser();
LogWriter lw1 = new LogWriter();
lw1.printMsg(hp.directUrlToCode(url));
}
First of all, manipulating an observable variable from outside of the JavaFX application thread is a bad idea. You won't be able to bind other variables to it (you'll get IllegalStateExceptions)
Second, I'd implement LogWriter like this:
// ...
public class LogWriter {
private final TextArea txtLog;
public LogWriter(TextArea txtLog) {
this.txtLog = txtLog;
}
void printMsg(final String s) {
if (!Platform.isFxApplicationThread()) {
Platform.runLater(new Runnable() {
#Override
public void run() {
printMsg(s);
}
});
} else {
txtLog.setText(txtLog.getText() + "\n" + s);
}
}
}
and use it this way:
//...
#FXML
private TextArea txtLog;
// ...
public void checkUrl() {
final String url = UrlInput.getText();
final LogWriter lw = new LogWriter(txtLog);
Task<String> task = new Task<String>() {
#Override
protected String call() {
lw.printMsg("loading website sourcecode...");
return HTMLParser.directUrlToCode(url);
}
#Override
protected void succeeded() {
super.succeeded();
lw.printMsg(getValue());
}
#Override
protected void failed() {
super.failed();
if (getException() != null) {
getException().printStackTrace();
}
lw.printMsg("failed!");
}
};
new Thread(task).start();
}
Note that HTMLParser does not need to extend Thread.