Java - How can I implement an Applet into a JavaFX component? [duplicate] - java

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.

Related

Run JavaFX app from the command line without GUI

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.

Using JNativeHook from an applet in browser

I am trying to use JNativeHook from a browser applet to grab a certain keyboard event. I am getting some strange behavior and it does not seem to be working. This is the code I have so far:
import java.awt.*;
import java.applet.Applet;
import netscape.javascript.*;
import org.jnativehook.GlobalScreen;
import org.jnativehook.NativeHookException;
import org.jnativehook.keyboard.NativeKeyEvent;
import org.jnativehook.keyboard.NativeKeyListener;
public class Test extends Applet implements NativeKeyListener {
JSObject window;
public void nativeKeyPressed(NativeKeyEvent e) {
window.eval("console.log('"+NativeKeyEvent.getKeyText(e.getKeyCode()) + "');");
}
public void nativeKeyReleased(NativeKeyEvent e) {
}
public void nativeKeyTyped(NativeKeyEvent e) {
}
public void init() {
window = JSObject.getWindow(this);
window.eval("console.log('test');");
try {
GlobalScreen.registerNativeHook();
}
catch (NativeHookException ex) {
window.eval("console.log('There was a problem registering the native hook.');");
window.eval("console.log('"+ex.getMessage()+"');");
System.exit(1);
}
//Construct the example object and initialze native hook.
GlobalScreen.getInstance().addNativeKeyListener(this);
}
}
Ideally I would like to be able to callback into a javascript function after a certain key is pressed globally. I have read some stuff about permissions and signing but I am not sure if this is causing an issue for localhost testing (I have to click through warnings).
I am also not 100% on the inner workings of JNativeHook. I am tempted to just write a small DLL for each platform using JNI, but I wanted to check to see if I was missing something fundamental first.
It is possible to run native code (JNativeHook) from JNLP but you need to sign the code with a valid certificate. You can run from localhost without one if you want to do some testing.

Is it possible to create programs in Java that create text to link in Chrome?

I apologize for the long question.
I was browsing a forum the other day and I saw a few pieces of text that were linking to youtube and other sites.
I had to always highlight and then copy and paste or right click "go to" in google chrome browser.
Since I've been playing with Java a little bit, I thought about making my own little program that will give a link to text that has an address . For example if I said "hey, check this video out I saw the other day 'www.youtube.com' " I'd want the youtube part to be clickable.
Could anybody tell me if such a thing is possible and if it is, what libraries would I have to use for this and lastly, how can I find a list of all imports and libraries in java?
Thanks.
Use HTML in JEditorPane and add HyperLinkListener to detect click on URLs.
Than use Desktop API to open default browser with the URL.
Something like:
import java.awt.Desktop;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
public class Test {
public static void main(String[] argv) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JEditorPane jep = new JEditorPane();
jep.setContentType("text/html");//set content as html
jep.setText("Welcome to <a href='http://stackoverflow.com/'>StackOverflow</a>.");
jep.setEditable(false);//so its not editable
jep.setOpaque(false);//so we dont see whit background
jep.addHyperlinkListener(new HyperlinkListener() {
#Override
public void hyperlinkUpdate(HyperlinkEvent hle) {
if (HyperlinkEvent.EventType.ACTIVATED.equals(hle.getEventType())) {
System.out.println(hle.getURL());
Desktop desktop = Desktop.getDesktop();
try {
desktop.browse(hle.getURL().toURI());
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
});
JFrame f = new JFrame("HyperlinkListener");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(jep);
f.pack();
f.setVisible(true);
}
});
}
}

VLCJ NullPointer (I just want a simple cross-platform java video player)

I am wanting to make a simple java applicaiton to play video. I want it to play mpeg4 and mov formats in particular. JMF is what I started with and I have a lovely working example. However, there is no support for mov or mpeg4 formats. I've looked at Xuggler but can't see a SIMPLE way to get it working. VLCJ seemed easy - I downloaded the jar files and attached them to my project (vlcj-2.1.0.jar, jna-3.4.0.jar, platform-3.4.0.jar, vlcj-2.1.0.jar)). I got the sample code and adapted it (below). But when I run the code, I get a java.lang.NullPointerException exception. I've tried adjusting the number and direciton of the slashes (forward and backward) in the filename. Nothing seems to work. Please could you help???
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.JFileChooser;
import uk.co.caprica.vlcj.component.EmbeddedMediaPlayerComponent;
import java.lang.Object;
import uk.co.caprica.vlcj.mrl.FileMrl;
import uk.co.caprica.vlcj.binding.LibVlc;
import uk.co.caprica.vlcj.runtime.RuntimeUtil;
import com.sun.jna.Native;
import com.sun.jna.NativeLibrary;
public class TestPlayer {
private final JFrame frame;
private EmbeddedMediaPlayerComponent mediaPlayer;
public static void loadLibs(){
NativeLibrary.addSearchPath(
RuntimeUtil.getLibVlcLibraryName(), "C:/Program Files/VideoLAN/VLC/"
);
Native.loadLibrary(RuntimeUtil.getLibVlcLibraryName(), LibVlc.class);
}
public static void main(final String[] args){
loadLibs();
final String mrl = "file://C:/Test.mov";
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new TestPlayer().run(mrl);
}
});
}
public TestPlayer(){
frame = new JFrame("test VLCJ");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocation(100,100);
frame.setSize(600,400);
frame.setVisible(true);
}
private void run(String mrl){
System.out.println(mrl);
try{
mediaPlayer.getMediaPlayer().playMedia(mrl);
}catch(Exception e){
System.err.println(e.toString());
}
}
}
I'm using VLC version 2.0.2 and VLCJ 2.1.0 sources and JDK 1.7 on windows 32 bit. I hope it's something simple...
It looks like you are using mediaPlayerwithout ever initializing it, thus causing a NullPointerException in run().
Try initializing it in your constructor.

browsing javascript

I want to write a simple web browser in java and here’s my code!
import javax.swing.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
public class WebBrowser extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
public JPanel
address_panel, window_panel;
public JLabel
address_label;
public JTextField
address_tf;
public JEditorPane
window_pane;
public JScrollPane
window_scroll;
public JButton
address_b;
private Go go = new Go();
public WebBrowser() throws IOException {
// Define address bar
address_label = new JLabel(" address: ", SwingConstants.CENTER);
address_tf = new JTextField("http://www.yahoo.com");
address_tf.addActionListener(go);
address_b = new JButton("Go");
address_b.addActionListener(go);
window_pane = new JEditorPane("http://www.yahoo.com");
window_pane.setContentType("text/html");
window_pane.setEditable(false);
address_panel = new JPanel(new BorderLayout());
window_panel = new JPanel(new BorderLayout());
address_panel.add(address_label, BorderLayout.WEST);
address_panel.add(address_tf, BorderLayout.CENTER);
address_panel.add(address_b, BorderLayout.EAST);
window_scroll = new JScrollPane(window_pane);
window_panel.add(window_scroll);
Container pane = getContentPane();
pane.setLayout(new BorderLayout());
pane.add(address_panel, BorderLayout.NORTH);
pane.add(window_panel, BorderLayout.CENTER);
setTitle("web browser");
setSize(800,600);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public class Go implements ActionListener{
public void actionPerformed(ActionEvent ae){
try {
window_pane.setPage(address_tf.getText());
} catch (MalformedURLException e) { // new URL() failed
window_pane.setText("MalformedURLException: " + e);
} catch (IOException e) { // openConnection() failed
window_pane.setText("IOException: " + e);
}
}
}
public static void main(String args[]) throws IOException {
WebBrowser wb = new WebBrowser();
}
}
It works fine for simple html pages but it cannot load JavaScript part of the code! My problem is what should I add to the code to load the javascripts? Thank you!
Swing's default widgets only have very basic support for HTML4 and CSS, with absolutely no support for JavaScript at all (by default). You could potentially use the built-in Rhino JavaScript engine to execute the code, but that would have to be done manually and would be pretty difficult. HtmlUnit uses this tactic to parse HTML pages and execute the JavaScript, but it has generally poor compatibility and completely lacks a renderer, so you'd have to write that yourself (i.e. no display, you only get access to the page content from code).
There's a few Swing-based browser widgets floating around which embed a Gecko (Firefox) or WebKit (Chrome/Safari) renderer and would thus be able to take advantage of proper JavaScript interpreters, but they're all buggy, expensive, or unmaintained. These would all support JavaScript but they generally use very old versions of the various browser engines and have poor compatibility with modern websites, in addition to lacking cross-platform compatibility.
Eclipse's SWT project includes a browser widget that appears to be actively maintained, but has a dependence on the SWT libraries and would be somewhat more difficult to use in a Swing application, though it may be possible. SWT is an entirely different UI toolkit from AWT/Swing (which you're currently using) and in order to take advantage of its browser widget, you'd have to find a way to embed it in a Swing app, or use only the SWT toolkit.
Overall, SWT's browser is probably your best bet for getting a decent browser in Java, but it may still be troublesome to use. Good luck!

Categories

Resources