I have a JavaFX in which the user can select files to be processed. Now I want to automate it so that you can run the application from the command line and pass those files as a parameter. I tried to do this:
java -jar CTester.jar -cl file.txt
public static void main(String[] args)
{
if (Arrays.asList(args).contains("-cl"))
{
foo();
}
else
{
launch(args);
}
}
The main is executed and the argument is correct, but this still creates the GUI.
From the docs:
The entry point for JavaFX applications is the Application class. The
JavaFX runtime does the following, in order, whenever an application
is launched:
Constructs an instance of the specified Application class
Calls the init() method
Calls the start(javafx.stage.Stage) method
Waits for the application to finish, which happens when either of the following
occur:
the application calls Platform.exit()
the last window has been closed and the implicitExit attribute on Platform is true
Calls the stop() method
So if I cannot use the main method, how can I create this "alterantive" flow? I thought about creating a normal java application as a wrapper but that seems a little bit overkill for such a simple task. Is there a more elegant way of doing this?
Simply exit the application after calling your foo() method:
Platform.exit();
Here is a quick sample application to demonstrate:
import javafx.application.Application;
import javafx.application.Platform;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class CLSample extends Application {
public static void main(String[] args) {
if (Arrays.asList(args).contains("-cl")) {
commandLine();
Platform.exit();
} else {
launch(args);
}
}
public static void commandLine() {
System.out.println("Running only command line version...");
}
#Override
public void start(Stage primaryStage) {
// Simple Interface
VBox root = new VBox(10);
root.setAlignment(Pos.CENTER);
root.setPadding(new Insets(10));
root.getChildren().add(new Label("GUI Loaded!"));
// Show the stage
primaryStage.setScene(new Scene(root));
primaryStage.setTitle("CLSample Sample");
primaryStage.show();
}
}
If you pass -cl, then only the commandLine() method gets called.
Related
I'm trying to launch a new process on a separate JVM via code following the method illustrated here:
Executing a Java application in a separate process
The code I'm using is the following (taken from the question above):
public static int exec(Class klass) throws IOException, InterruptedException {
String javaHome = System.getProperty("java.home");
String javaBin = javaHome +
File.separator + "bin" +
File.separator + "java";
String classpath = System.getProperty("java.class.path");
String className = klass.getName();
ProcessBuilder builder = new ProcessBuilder(javaBin,"-cp",classpath,className);
Process process = builder.inheritIO().start();
process.waitFor();
return process.exitValue();
}
...in which klass is the class I want to launch.
This would work for a normal Java process, but the problem is that I'm trying to launch a JavaFX application, and the code above generates the following error:
Error: JavaFX runtime components are missing, and are required to run this application
So, to add the JavaFX modules, I tried including the --module-path and --add-modules commands in the declaration of builder, I even attempted copying and pasting the entire execution command, and I kept getting this other error:
Unrecognized option: (command string with modules)
Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.
How could I solve this?
Let me know if details are needed.
Since the advent of modules, there are at least three different ways a JavaFX application can be configured:
Put everything on the module-path, including the JavaFX modules and your module.
This is the ideal situation but not always possible/viable (e.g. because of incompatible dependencies).
Put the JavaFX modules on the module-path and your own code on the class-path.
This configuration requires the use of --add-modules.
Put everything on the class-path, including the JavaFX modules and your own code.
With this configuration your main class cannot be a subtype of Application. Otherwise you get the error you mentioned in your question: "Error: JavaFX runtime components are missing, and are required to run this application".
This configuration allows for easy use of so-called fat/uber JARs.
Warning: This approach is explicitly unsupported.
The command line used with ProcessBuilder will depend on which configuration your application uses. You also have to take into account any other options passed the command line, such as the default encoding or locale. Unfortunately, your question doesn't provide enough information to tell what exactly is going wrong. The error you mention makes me think you're using the third configuration, but I can't be sure.
That said, I'll give some examples of launching the same application from within the application; you should be able to modify things to fit your needs. Note I used Java/JavaFX 13.0.1 when testing the below code.
Configuration #1
Put everything on the module-path.
module-info.java:
module app {
requires javafx.controls;
exports com.example.app to
javafx.graphics;
}
Main.java:
package com.example.app;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Path;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import static java.lang.System.getProperty;
public class Main extends Application {
private static void launchProcess() {
try {
new ProcessBuilder(
Path.of(getProperty("java.home"), "bin", "java").toString(),
"--module-path",
getProperty("jdk.module.path"),
"--module",
getProperty("jdk.module.main") + "/" + getProperty("jdk.module.main.class"))
.inheritIO()
.start();
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
}
#Override
public void start(Stage primaryStage) {
Button launchBtn = new Button("Launch process");
launchBtn.setOnAction(
event -> {
event.consume();
launchProcess();
});
primaryStage.setScene(new Scene(new StackPane(launchBtn), 500, 300));
primaryStage.setTitle("Multi-Process Example");
primaryStage.show();
}
}
Command line:
java --module-path <PATH> --module app/com.example.app.Main
Replace "<PATH>" with a path containing both the JavaFX modules and the above module.
Configuration #2
Put JavaFX modules on the module-path and your code on the class-path.
Main.java:
package com.example.app;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Path;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import static java.lang.System.getProperty;
public class Main extends Application {
private static void launchProcess() {
try {
new ProcessBuilder(
Path.of(getProperty("java.home"), "bin", "java").toString(),
"--module-path",
getProperty("jdk.module.path"),
"--add-modules",
"javafx.controls",
"--class-path",
getProperty("java.class.path"),
Main.class.getName())
.inheritIO()
.start();
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
}
#Override
public void start(Stage primaryStage) {
Button launchBtn = new Button("Launch process");
launchBtn.setOnAction(
event -> {
event.consume();
launchProcess();
});
primaryStage.setScene(new Scene(new StackPane(launchBtn), 500, 300));
primaryStage.setTitle("Multi-Process Example");
primaryStage.show();
}
}
Command line:
java --module-path <M_PATH> --add-modules javafx.controls --class-path <C_PATH> com.example.app.Main
Replace "<M_PATH>" with a path containing the JavaFX modules and replace "<C_PATH>" with a path containing the above code.
Configuration #3
Put everything on the class-path. Note the main class (now Launcher) is not a subclass of Application.
Launcher.java:
package com.example.app;
import javafx.application.Application;
public class Launcher {
public static void main(String[] args) {
Application.launch(Main.class, args);
}
}
Main.java:
package com.example.app;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Path;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import static java.lang.System.getProperty;
public class Main extends Application {
private static void launchProcess() {
try {
new ProcessBuilder(
Path.of(getProperty("java.home"), "bin", "java").toString(),
"--class-path",
getProperty("java.class.path"),
Launcher.class.getName())
.inheritIO()
.start();
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
}
#Override
public void start(Stage primaryStage) {
Button launchBtn = new Button("Launch process");
launchBtn.setOnAction(
event -> {
event.consume();
launchProcess();
});
primaryStage.setScene(new Scene(new StackPane(launchBtn), 500, 300));
primaryStage.setTitle("Multi-Process Example");
primaryStage.show();
}
}
Command line:
java --class-path <PATH> com.example.app.Launcher
Replace "<PATH>" with a path containing the JavaFX JARs and the above code.
I have an issue with JavaFX and multithreading. Basically I have an application and the task at hand asks me that I should have multiple users. Like for example I have a bug-testing application which shows a list of bugs and users and testers can choose to add/delete bugs from this list(a tableview in my case). Building the application was not a problem, but I don't understand how to 'simulate' multiple users. The task says that when I run my program, 3 windows should appear(2 for users and 1 for a tester), and when I add/delete a bug, the tableview should get updated.
I believe I need to do this with threads, as my last course involved multithreading, but I'm at a loss here. My main class looks like this:
import controller.OfertaCtrl;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
import repository.OfertaRepo;
import view.OfertaFXML;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Main extends Application {
private static Stage primaryStage;
private static Scene MyPage;
#Override
public void start(Stage primaryStage) throws Exception{
//Platform.setImplicitExit(false);
Main.primaryStage = primaryStage;
setPage();
}
public void setPage() throws IOException {
primaryStage.setTitle("Oferte");
FXMLLoader loader = new FXMLLoader(getClass().getResource("oferta.fxml"));
Pane pane = loader.load();
pane.setId("pane");
MyPage = new Scene(pane);
OfertaRepo repo = new OfertaRepo("C:\\Users\\Mihai\\workspace\\lalal\\newGUI\\src\\oferte.txt");
OfertaCtrl ctrl = new OfertaCtrl(repo);
OfertaFXML ctrl2 = loader.getController();
ctrl2.loadData(ctrl);
primaryStage.setScene(MyPage);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
So basically I take a list of 'offers' in this example from a .txt file and put them in an ObservableArrayList with which I work with in my Controller class. The problem lies in the fact that I don't understand how I need to run multiple threads of the same application. Also, how would I update my tableview for all windows when I modify it in an open window? I was thinking of doing light pooling on my ObservableArrayList and checking for alterations every 1 second or so.
I can provide more information or whatever is needed, I just need a few points on how to go about solving this problem.
Here's how the application looks right now:
Pretty much, I'm trying to write a simple program that lets the user choose a file. Unfortunately, JFileChooser through Swing is a little outdated, so I am trying to use JavaFX FileChooser for this. The goal is to run FileGetter as a thread, transfer the file data to the Main Class, and continue from there.
Main Class:
package application;
import java.io.File;
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
public class Main {
public static void main(String[] args) {
Thread t1 = new Thread(new FileGetter());
FileGetter fg = new FileGetter();
t1.start();
boolean isReady = false;
while(isReady == false){
isReady = FileGetter.getIsReady();
}
File file = FileGetter.getFile();
System.out.println(file.getAbsolutePath());
...
}
}
FileGetter Class:
package application;
import java.io.File;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
public class FileGetter extends Application implements Runnable {
static File file;
static boolean isReady = false;
#Override
public void start(Stage primaryStage) {
try {
FileChooser fc = new FileChooser();
while(file == null){
file = fc.showOpenDialog(primaryStage);
}
isReady = true;
Platform.exit();
} catch(Exception e) {
e.printStackTrace();
}
}
#Override
public void run() {
launch();
}
public static boolean getIsReady(){
return isReady;
}
public static File getFile(){
return file;
}
}
Problem is that the value of isReady in the while loop doesn't update to true when the user picked a file (the reason I have it is to prevent the code in Main from continuing with a File set to null).
Any help, alternative suggestions, or explanations as of why this happens is very much appreciated!
The java memory model does not require variable values to be the same in different threads except under specific conditions.
What is happening here is that the FileGetter thread is updating the value in the own memory that is only accessed from this thread, but your main thread doesn't see the updated value, since it only sees the version of the variable stored in it's own memory that is different from the one of the FileGetter thread. Each of the threads has it's own copy of the field in memory, which is perfectly fine according to the java specification.
To fix this, you can simply add the volatile modifier to isReady:
static volatile boolean isReady = false;
which makes sure the updated value will be visible from your main thread.
Furthermore I recommend reducing the number of FileGetter instances you create. In your code 3 instances are created, but only 1 is used.
Thread t1 = new Thread(() -> Application.launch(FileGetter.class));
t1.start();
...
The easiest way to implement this
Instead of trying to drive the horse with the cart, why not just follow the standard JavaFX lifecycle? In other words, make your Main class a subclass of Application, get the file in the start() method, and then proceed (in a background thread) with the rest of the application?
public class Main extends Application {
#Override
public void init() {
// make sure we don't exit when file chooser is closed...
Platform.setImplicitExit(false);
}
#Override
public void start(Stage primaryStage) {
File file = null ;
FileChooser fc = new FileChooser();
while(file == null){
file = fc.showOpenDialog(primaryStage);
}
final File theFile = file ;
new Thread(() -> runApplication(theFile)).start();
}
private void runApplication(File file) {
// run your application here...
}
}
What is wrong with your code
If you really want the Main class to be separate from the JavaFX Application class (which doesn't really make sense: once you have decided to use a JavaFX FileChooser, you have decided you are writing a JavaFX application, so the startup class should be a subclass of Application), then it gets a bit tricky. There are several issues with your code as it stands, some of which are addressed in other answers. The main issue, as shown in Fabian's answer, is that you are referencing FileGetter.isReady from multiple threads without ensuring liveness. This is exactly the issue addressed in Josh Bloch's Effective Java (Item 66 in the 2nd edition).
Another issue with your code is that you won't be able to use the FileGetter more than once (you can't call launch() more than once), which might not be an issue in your code now, but almost certainly will be at some point with this application as development progresses. The problem is that you have mixed two issues: starting the FX toolkit, and retrieving a File from a FileChooser. The first thing must only be done once; the second should be written to be reusable.
And finally your loop
while(isReady == false){
isReady = FileGetter.getIsReady();
}
is very bad practice: it checks the isReady flag as fast as it possibly can. Under some (fairly unusual) circumstances, it could even prevent the FX Application thread from having any resources to run. This should just block until the file is ready.
How to fix without making Main a JavaFX Application
So, again only if you have a really pressing need to do so, I would first create a class that just has the responsibility of starting the FX toolkit. Something like:
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.stage.Stage;
public class FXStarter extends Application {
private static final AtomicBoolean startRequested = new AtomicBoolean(false);
private static final CountDownLatch latch = new CountDownLatch(1);
#Override
public void init() {
Platform.setImplicitExit(false);
}
#Override
public void start(Stage primaryStage) {
latch.countDown();
}
/** Starts the FX toolkit, if not already started via this method,
** and blocks execution until it is running.
**/
public static void startFXIfNeeded() throws InterruptedException {
if (! startRequested.getAndSet(true)) {
new Thread(Application::launch).start();
}
latch.await();
}
}
Now create a class that gets a file for you. This should ensure the FX toolkit is running, using the previous class. This implementation allows you to call getFile() from any thread:
import java.io.File;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import javafx.application.Platform;
import javafx.stage.FileChooser;
public class FileGetter {
/**
** Retrieves a file from a JavaFX File chooser. This method can
** be called from any thread, and will block until the user chooses
** a file.
**/
public File getFile() throws InterruptedException {
FXStarter.startFXIfNeeded() ;
if (Platform.isFxApplicationThread()) {
return doGetFile();
} else {
FutureTask<File> task = new FutureTask<File>(this::doGetFile);
Platform.runLater(task);
try {
return task.get();
} catch (ExecutionException exc) {
throw new RuntimeException(exc);
}
}
}
private File doGetFile() {
File file = null ;
FileChooser chooser = new FileChooser() ;
while (file == null) {
file = chooser.showOpenDialog(null) ;
}
return file ;
}
}
and finally your Main is just
import java.io.File;
public class Main {
public static void main(String[] args) throws InterruptedException {
File file = new FileGetter().getFile();
// proceed...
}
}
Again, this is pretty complex; I see no reason not to simply use the standard FX Application lifecycle for this, as in the very first code block in the answer.
In this code
while(isReady == false){
isReady = FileGetter.getIsReady();
}
there is nothing that is going to change the state of FileGetter's isReady to true
I can't seem to find anything on this - other than it can't be embedded in a web view.
I currently have an image viewing product which is accessed via an applet and controlled via JavaScript from an HTML page.
I am investigating a client application using JavaFX and it would likely need to access that applet. I attempted to embed it into the WebView and that didn't work. Searching on this site stated that webview doesn't support plug in technology. This is to build an applet with Java FX - but rather to invoke and interact with an existing product.
Therefore I am left wondering if there is another way - using JavaFX 8?
Thanks!
A quick trial with a really simple sample applet, demonstrates that it is possible to embed Swing applets into JavaFX applications (with Java 8).
Sample
Here is the HelloWorld applet from the Oracle getting started with applets documentation:
import javax.swing.*;
public class HelloWorldApplet extends JApplet {
public void init() {
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
JLabel lbl = new JLabel("Hello World");
add(lbl);
}
});
} catch (Exception e) {
System.err.println("createGUI didn't complete successfully");
}
}
}
And here is a JavaFX application which embeds it:
import javafx.application.Application;
import javafx.embed.swing.SwingNode;
import javafx.scene.*;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javax.swing.JApplet;
import javax.swing.SwingUtilities;
import java.awt.Dimension;
import java.util.concurrent.*;
public class JavaFXSwingAppletHolderApplication extends Application {
private JApplet applet = new HelloWorldApplet();
private Dimension appletSize;
#Override public void init() throws ExecutionException, InterruptedException {
applet.init();
FutureTask<Dimension> sizingTask = new FutureTask<>(() ->
applet.getRootPane().getPreferredSize()
);
SwingUtilities.invokeLater(sizingTask);
appletSize = sizingTask.get();
}
#Override public void start(Stage stage) {
final SwingNode swingNode = new SwingNode();
SwingUtilities.invokeLater(() ->
swingNode.setContent(applet.getRootPane())
);
stage.setScene(
new Scene(
new Group(swingNode),
appletSize.getWidth(), appletSize.getHeight(),
Color.BLACK
)
);
stage.show();
}
#Override public void stop() {
applet.stop();
applet.destroy();
}
public static void main(String[] args) {
launch(args);
}
}
Notes
I'm not sure if the sizingTask is the above code is strictly necessary, I just stuck it in there just in case as I know little about Swing layout, so thought it best to be explicit.
This sample only embeds a basic applet, your applet will be more complex so you will need to validate a similar solution for your particular applet to ensure it works for you.
Recommendation
Most existing applets are quite small - it is probably a better idea to reimplement an applet as a pure JavaFX component implementation rather than try to embed the applet in a JavaFX application.
Also note that the applet API is deprecated as part of Java 9, by JEP 289: Deprecated the Applet API.
I am using JAVA FXML GUI to parse a text file. The user can select which file to parse and then press "load". When the user clicks on "load" the file gets parse and many lines gets added to an ArrayList. The user then search and manipulate the text that was parse that is store in the ArrayList.
Sometimes while loading/writing the file to the ArrayList or manipulating some lines, the GUI is not responsive. How can I separate the GUI process vs. the ArrayList handling in order for the GUI to always be accessible to the user ?
The code below launches my application:
package javafxapp;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class Javafxapp 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();
FXMLDocumentController controller = new FXMLDocumentController();
controller.openingSound();
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
This is a textbook case for the use of multithreading.
See this JavaFX documentation for information and tutorials on how to begin using it.