JavaFX Exception in Main Constructor due to ArrayList - java

I am new to programming JavaFx and now in my initial stages i am building an addressbook in javaFX but problem presist that It throws an exception in constructor of Main Class.
When i use ObserverableList i dont get any kind of Exception, while when i try to use array to store Entity Objects i got Exception.
Can anybody give me a solution to that problem?
The main thing i want to do is to save ObserverableList or ArrayList object to a file.
package com.company;
import com.company.Controllers.DatabaseConnectJDBC;
import com.company.Controllers.MainWindowController;
import com.company.Controllers.secondWindowController;
import com.company.Model.EmployeeEntity;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
import java.io.*;
import java.util.ArrayList;
public class Main extends Application {
Stage primaryStage;
#Override
public void start(Stage primaryStage) throws Exception {
this.primaryStage=primaryStage;
mainWindow();
}
public void mainWindow() {
try{
FXMLLoader loader=new FXMLLoader(this.getClass().getResource("Views/MainWindow.fxml"));
AnchorPane pane=loader.load();
Scene scene=new Scene(pane);
MainWindowController controller=loader.getController();
controller.setMain(this);
primaryStage.setScene(scene);
primaryStage.setResizable(false);
primaryStage.show();
}catch (Exception e){
e.printStackTrace();
}
}
public void secondaryWindow() {
try{
FXMLLoader loader=new FXMLLoader(this.getClass().getResource("Views/secondaryWindow.fxml"));
AnchorPane pane=loader.load();
Scene scene=new Scene(pane);
Stage secondaryStage=new Stage();
secondWindowController controller=loader.getController();
controller.setMain(this,secondaryStage);
secondaryStage.setScene(scene);
secondaryStage.setResizable(false);
secondaryStage.show();
}catch (Exception e){
e.printStackTrace();
}
}
private ObservableList<EmployeeEntity> employeeObserveList= FXCollections.observableArrayList();
private ArrayList<EmployeeEntity> arrayList;
public ObservableList<EmployeeEntity> getEmployeeObserveList(){return employeeObserveList;}
public void setEmployeeObserveList(EmployeeEntity person){
getEmployeeObserveList().add(person);
}
public Main()
{
arrayList.add(new EmployeeEntity("3","126-B Millat Town","030123456","Abubaker","Usman"));
arrayList.add(new EmployeeEntity("4","127-B Millat Town","032123456","Asma","Rasool"));
arrayList.add(new EmployeeEntity("5","128-B Millat Town","035123456","Talha","Farooq"));
employeeObserveList = FXCollections.observableArrayList(arrayList);
employeeObserveList.addAll(arrayList);
}
Exception
Exception in Application constructor
Exception in thread "main" java.lang.RuntimeException: Unable to construct Application instance: class com.company.Main
at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:907)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$156(LauncherImpl.java:182)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(LauncherImpl.java:819)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$176(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl.lambda$null$174(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$175(PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$149(WinApplication.java:191)
... 1 more
Caused by: java.lang.NullPointerException
at com.company.Main.<init>(Main.java:68)
... 13 more

change this line
private ArrayList<EmployeeEntity> arrayList;
To
private List<EmployeeEntity> arrayList = new ArrayList<EmployeeEntity>();
You never initialized ArrayList.

Related

I'm trying to import an fxml file into my main class and Parent root = FXMLLoader.load(getClass().getResource()); returns null

I'm trying to import an fxml file into my main class and Parent root = FXMLLoader.load(getClass().getResource(/View/Main_Form.fxml)); returns null.
It basically is telling me that it can't find the "Main_Form.fxml" file that I am asking it to find.
I have it in a package labeled "View" which is the path I specified.
code is as follows:
`package com.example.c482_1;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class HelloApplication extends Application {
#Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("/view/Main_Form.fxml"));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch();
}
}`
file structure of the project
I have tried checking the path, I made my main project the resource root with no luck as well.
Not quite sure but I would try checking to make sure the path is relative

JavaFX error "Application launch must not be called more than once" while running 2 Test cases

I am using JavaFX to write a sample video player. But the tests fails when run together, ( Note: individually test passes).
Error: Unexpected exception thrown: java.lang.IllegalStateException: Application launch must not be called more than once
I understand that calling launch() twice on same Application Instance is causing this issue as per this . But I am not able to understand, that after one test completes, why the app is still running ? Why new instance is not getting created for 2nd test. testUnsupportedVideoFileThrowsError() succeeds but testSupportedVideoFilePlaysSuccessfully() fails.
package media;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.media.MediaView;
import javafx.stage.Stage;
import java.io.File;
public class PlayVideoSnippet extends Application {
private static String source;
private Media media = null;
private MediaPlayer mediaPlayer = null;
private MediaView mediaView = null;
private Scene scene = null;
public static void playVideo(String source) {
PlayVideoSnippet.source = source;
PlayVideoSnippet.launch();
}
#Override
public void start(Stage stage) throws InterruptedException {
try {
media = new Media(new File(source).toURI().toString());
//onError close the app
media.setOnError(() -> {
Platform.exit();
});
//Create MediaPlayer, with media
mediaPlayer = new MediaPlayer(media);
mediaPlayer.setAutoPlay(true);
//onEnd of media, close the app
mediaPlayer.setOnEndOfMedia(() -> {
Platform.exit();
});
//Create media viewer
mediaView = new MediaView(mediaPlayer);
//create scene
scene = new Scene(new Group(), media.getWidth(), media.getHeight());
stage.setScene(scene);
stage.setTitle("Video Player");
//attach the mediaView to the scene root
((Group) scene.getRoot()).getChildren().add(mediaView);
stage.show();
} finally {
System.out.println("Inside finally");
stage.close();
}
}
}
package media;
import javafx.scene.media.MediaException;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class PlayVideoSnippetTest {
/**
* Tests for {#link PlayVideoSnippet#playVideo(String)}.
*/
final String PATH_OF_SUPPORTED_VIDEO_FILE = "src/test/resources/file_example_MP4_480_1_5MG.mp4";
final String PATH_OF_UNSUPPORTED_VIDEO_FILE = "src/test/resources/file_example_WMV_480_1_2MB.wmv";
#Test
void testSupportedVideoFilePlaysSuccessfully() {
assertDoesNotThrow(() -> PlayVideoSnippet.playVideo(PATH_OF_SUPPORTED_VIDEO_FILE));
}
#Test
void testUnsupportedVideoFileThrowsError() {
RuntimeException exception = assertThrows(RuntimeException.class, () -> PlayVideoSnippet.playVideo(PATH_OF_UNSUPPORTED_VIDEO_FILE));
assertTrue(exception.getCause().getClass().equals(MediaException.class));
}
}
I was able to fix the issue with help of below inputs:
Using TestFX for testing purpose as suggested by #jewelsea.
Inputs from #James_D
StackOver flow issue
ApplicationTest.launch() method internally takes care of setting up primary stage and cleaning before each test.
Solution:
import org.junit.jupiter.api.Test;
import org.testfx.framework.junit5.ApplicationTest;
class VideoTest extends ApplicationTest {
final String pathOfSupportedFile = "video.mp4";
final String pathOfUnsupportedFile = "video.wmv";
#Test
void testSupportedVideoFilePlaysSuccessfully() throws Exception {
assertDoesNotThrow(() -> PlayVideoSnippetTest.launch(PlayVideoSnippet.class,
new String[]{pathOfSupportedFile}));
}
#Test
void testUnsupportedVideoFileThrowsError() throws Exception {
RuntimeException exception = assertThrows(RuntimeException.class,
() -> PlayVideoSnippetTest.launch(PlayVideoSnippet.class,
new String[]{pathOfUnsupportedFile}));
assertTrue(exception.getCause().getCause().getClass().equals(MediaException.class));
}
}

Exception handling in static initializer

Normally I handle my exceptions by showing some custom Alert (JavaFX) with details, but JavaFX runtime is not initialized at all when the static initializer of my class runs.
Is there any way to handle such exception without printing its content to output like an animal?
public class MyStaticInitializedClass {
static {
try {
//do the things that may throw exception
} catch(Exception ex) {
ExceptionHandler.showException(ex);
}
}
}
public class ExceptionHandler {
public static void showException(Exception ex) {
//constructs JavaFX alert with exception details
alert.show();
}
}
First consder if you shouldn't let the application simply crash and log the reason. A failure in a static initializer typically means there's something seriously wrong with the environment, which is not likely something you can recover from. Also, as far as I know, once a class fails to load it can't ever be loaded by the same ClassLoader again.
That said, if you want to show errors to your user in an alert, even if the error occurs before the JavaFX runtime has been initialized, then you need to save the error somewhere. Then, once you launch JavaFX, check wherever you stored the error(s) and show them. For example:
Main.java:
import javafx.application.Application;
public class Main {
public static void main(String[] args) {
// an "error" before JavaFX is launched
App.notifyUserOfError(new RuntimeException("OOPS!"));
Application.launch(App.class, args);
}
}
App.java:
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayDeque;
import java.util.Objects;
import java.util.Queue;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.layout.Priority;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.stage.Stage;
public class App extends Application {
private static Queue<Throwable> errorQueue;
private static App appInstance;
public static synchronized void notifyUserOfError(Throwable throwable) {
Objects.requireNonNull(throwable);
if (appInstance == null) {
if (errorQueue == null) {
errorQueue = new ArrayDeque<>();
}
errorQueue.add(throwable);
} else {
if (Platform.isFxApplicationThread()) {
appInstance.showErrorAlert(throwable);
} else {
Platform.runLater(() -> appInstance.showErrorAlert(throwable));
}
}
}
private static synchronized Queue<Throwable> setAppInstance(App instance) {
if (appInstance != null) {
throw new IllegalStateException();
}
appInstance = instance;
var queue = errorQueue;
errorQueue = null; // no longer needed
return queue;
}
private Stage primaryStage;
#Override
public void start(Stage primaryStage) {
this.primaryStage = primaryStage;
var scene = new Scene(new StackPane(new Label("Hello, World!")), 600, 400);
primaryStage.setScene(scene);
primaryStage.show();
var errors = setAppInstance(this);
if (errors != null) {
// if non-null then should be non-empty
do {
showErrorAlert(errors.remove());
} while (!errors.isEmpty());
// possibly exit the application if you can't recover
}
}
private void showErrorAlert(Throwable error) {
var alert = new Alert(AlertType.ERROR);
alert.initOwner(primaryStage);
alert.setContentText(error.toString());
var sw = new StringWriter();
error.printStackTrace(new PrintWriter(sw));
var area = new TextArea(sw.toString());
area.setEditable(false);
area.setFont(Font.font("Monospaced", 12));
var details = new VBox(5, new Label("Stack trace:"), area);
VBox.setVgrow(area, Priority.ALWAYS);
alert.getDialogPane().setExpandableContent(details);
alert.showAndWait();
}
}
The above puts the error in a queue if JavaFX has not been initialized yet. At the end of the start method the queue is checked for any errors and they're displayed to the user one after the other. If JavaFX has already been initialized then the error is immediately shown to the user.

JavaFX Exception in thread "WindowsNativeRunloopThread" java.lang.NoSuchMethodError: <init>

I just wrote this code here:
package SpellcheckerClient;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
public class Main extends Application {
#Override
public void start(Stage primaryStage) {
try {
BorderPane root = FXMLLoader.load(getClass().getResource("/controller/gui.fxml"));
Scene scene = new Scene(root);
scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
primaryStage.setScene(scene);
primaryStage.setTitle("Spellchecker Client");
primaryStage.show();
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}
And this is the corresponding controller.
package controller;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import spellchecker.remote.SpellcheckerRemoteAdapter;
public class Controller {
#FXML
TextField input;
#FXML
Button send;
#FXML
TextArea area;
#FXML
Button connect;
private SpellcheckerRemoteAdapter adapter;
#FXML
private void send() throws RemoteException{
String toCheck = input.getText();
this.area.appendText(toCheck + "\n");
this.area.appendText(checkRoutine(toCheck, this.adapter) + "\n\n");
this.input.clear();
}
public void initiateConnection() {
try {
Registry registry = LocateRegistry.getRegistry(1088);
this.adapter = (SpellcheckerRemoteAdapter) registry.lookup(SpellcheckerRemoteAdapter.NAME);
this.area.appendText("Verbindung erfolgreich aufgebaut!\n");
connect.setDisable(true);
} catch (Exception e) {
if(this.adapter == null) {
this.area.appendText("Server nicht gefunden!\n");
}
}
}
private static String checkRoutine(String input, SpellcheckerRemoteAdapter adapter) throws RemoteException {
if (input == null || input.isEmpty()) {
return "Bitte etwas eingeben!";
}
String[] words = input.split(" ");
boolean control = true;
String output = "";
for(String word : words) {
if(!adapter.check(word)) {
control = false;
output += word + ":\t" + adapter.getProposal(word) + "\n";
}
}
if(control) {
return "Alles Okay!\n";
}
return output;
}
}
If I run this code on my Laptop, where I wrote it, it runs perfectly fine in Eclipse and as runnable Jar. However, if I try to run the JAR on another computer i receive this error message:
Exception in thread "WindowsNativeRunloopThread" java.lang.NoSuchMethodError: <init>
at javafx.graphics/com.sun.glass.ui.win.WinApplication.staticScreen_getScreens(Native Method)
at javafx.graphics/com.sun.glass.ui.Screen.initScreens(Unknown Source)
at javafx.graphics/com.sun.glass.ui.Application.lambda$run$1(Unknown Source)
at javafx.graphics/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at javafx.graphics/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(Unknown Source)
at java.base/java.lang.Thread.run(Unknown Source)
Exception in thread "WindowsNativeRunloopThread" java.lang.NoSuchMethodError: <init>
at javafx.graphics/com.sun.glass.ui.win.WinApplication.staticScreen_getScreens(Native Method)
at javafx.graphics/com.sun.glass.ui.Screen.initScreens(Unknown Source)
at javafx.graphics/com.sun.glass.ui.Application.lambda$run$1(Unknown Source)
at javafx.graphics/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at javafx.graphics/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(Unknown Source)
at java.base/java.lang.Thread.run(Unknown Source)
Exception in thread "JavaFX Application Thread" java.lang.NullPointerException
at javafx.graphics/com.sun.prism.d3d.D3DPipeline.getAdapterOrdinal(Unknown Source)
at javafx.graphics/com.sun.javafx.tk.quantum.QuantumToolkit.assignScreensAdapters(Unknown Source)
at javafx.graphics/com.sun.javafx.tk.quantum.QuantumToolkit.runToolkit(Unknown Source)
at javafx.graphics/com.sun.javafx.tk.quantum.QuantumToolkit.lambda$startup$10(Unknown Source)
at javafx.graphics/com.sun.glass.ui.Application.lambda$run$1(Unknown Source)
at javafx.graphics/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at javafx.graphics/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(Unknown Source)
at java.base/java.lang.Thread.run(Unknown Source)
On my Laptop and my Computer are the same Versions of the JDK/JRE installed.
I don't really get what the error message is telling me.
Hello I have the same issue on my Eclipse environnement (Windows 10 OS),
adding in VM option -Djava.library.path="C:\WINDOWS\Sun\Java\bin" solved my problem
That means that javafx-graphics-[version]-win.jar call some native dll. And You have to found were those dll is stored.
I found the path, thanks to jvisualvm and showing the VM option for the case where it's the application run correctly.
Hoping that it will solve your problem.
Which JDk you have installed?? I have the same issue and i use JDK 8 instead of JDK 9. Which helped me.Sample Image of Exception
This is because jar which i created it was created on JDK 8 through a different system.
Where as when it was executing on another system which has JDK9. So it is version incompatible.
After keeping single JDK 8 and mapped it to system environment when i try to run my jar it worked for me.
Good Luck :)

Accessing java fx clipboard from a commandline application?

This might be a stupid question from a newbie, so bear with me. Here is what I did:
import javafx.scene.input.Clipboard;
import javafx.scene.input.ClipboardContent;
import javax.sound.sampled.Clip;
public class Main {
public static void main(String[] args) {
final Clipboard clipboard = Clipboard.getSystemClipboard();
final ClipboardContent content = new ClipboardContent();
content.putHtml("<b>Some bold html</b>");
clipboard.setContent(content);
}
}
I got the following error:
/Library/Java/JavaVirtualMachines/jdk1.8.0_11.jdk/Contents/Home/bin/java -Didea.launcher.port=7532 "-Didea.launcher.bin.path=/Applications/IntelliJ IDEA 13 CE.app/bin" -Dfile.encoding=UTF-8 -classpath "/Library/Java/JavaVirtualMachines/jdk1.8.0_11.jdk/Contents/Home/lib/ant-javafx.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_11.jdk/Contents/Home/lib/dt.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_11.jdk/Contents/Home/lib/javafx-mx.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_11.jdk/Contents/Home/lib/jconsole.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_11.jdk/Contents/Home/lib/sa-jdi.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_11.jdk/Contents/Home/lib/tools.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_11.jdk/Contents/Home/jre/lib/charsets.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_11.jdk/Contents/Home/jre/lib/deploy.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_11.jdk/Contents/Home/jre/lib/htmlconverter.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_11.jdk/Contents/Home/jre/lib/javaws.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_11.jdk/Contents/Home/jre/lib/jce.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_11.jdk/Contents/Home/jre/lib/jfr.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_11.jdk/Contents/Home/jre/lib/jfxswt.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_11.jdk/Contents/Home/jre/lib/jsse.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_11.jdk/Contents/Home/jre/lib/management-agent.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_11.jdk/Contents/Home/jre/lib/plugin.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_11.jdk/Contents/Home/jre/lib/resources.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_11.jdk/Contents/Home/jre/lib/rt.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_11.jdk/Contents/Home/jre/lib/ext/cldrdata.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_11.jdk/Contents/Home/jre/lib/ext/dnsns.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_11.jdk/Contents/Home/jre/lib/ext/jfxrt.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_11.jdk/Contents/Home/jre/lib/ext/localedata.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_11.jdk/Contents/Home/jre/lib/ext/nashorn.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_11.jdk/Contents/Home/jre/lib/ext/sunec.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_11.jdk/Contents/Home/jre/lib/ext/sunjce_provider.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_11.jdk/Contents/Home/jre/lib/ext/sunpkcs11.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_11.jdk/Contents/Home/jre/lib/ext/zipfs.jar:/Users/kaiyin/IdeaProjects/untitled8/out/production/untitled8:/Applications/IntelliJ IDEA 13 CE.app/lib/idea_rt.jar" com.intellij.rt.execution.application.AppMain com.company.Main
Picked up _JAVA_OPTIONS: -Dawt.useSystemAAFontSettings=lcd -Dsun.java2d.xrender=true
Exception in thread "main" java.lang.IllegalStateException: This operation is permitted on the event thread only; currentThread = main
at com.sun.glass.ui.Application.checkEventThread(Application.java:432)
at com.sun.glass.ui.ClipboardAssistance.<init>(ClipboardAssistance.java:40)
at com.sun.javafx.tk.quantum.QuantumToolkit.getSystemClipboard(QuantumToolkit.java:1127)
at javafx.scene.input.Clipboard.getSystemClipboardImpl(Clipboard.java:410)
at javafx.scene.input.Clipboard.getSystemClipboard(Clipboard.java:175)
at com.company.Main.main(Main.java:10)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
Process finished with exit code 1
Is it possible to access javafx cliboard without creating a gui at all?
I'll ignore the question of why you would ever want to do this...
As pointed out in the comments, you need to start the FX Application Thread in order to access the JavaFX clipboard. However, you don't actually need to show a Stage at any point.
The following compiles and runs:
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.input.Clipboard;
import javafx.scene.input.ClipboardContent;
import javafx.stage.Stage;
public class ClipboardTest extends Application {
#Override
public void start(Stage primaryStage) {
final Clipboard clipboard = Clipboard.getSystemClipboard();
final ClipboardContent content = new ClipboardContent();
content.putHtml("<b>Some bold html</b>");
clipboard.setContent(content);
Platform.exit();
}
public static void main(String[] args) {
launch(args);
}
}

Categories

Resources