I'm trying to load an applet on a simple HTML page that I've written (I also wrote the applet) but it throws an InvocationTargetException every time. The applet works when I run it in Eclipse, but I can't get it to work on the webpage.
HTML:
<html>
<center>
<applet archive = "OneMove.jar" code = "main.TheApplet.class" width = "1000" height = "500"></applet>
</center>
</html>
TheApplet.class:
package main;
import java.awt.BorderLayout;
import java.lang.reflect.InvocationTargetException;
import javax.swing.*;
public class TheApplet extends JApplet {
private static final long serialVersionUID = 7088647188194272265L;
protected Display display0 = new Display();
public void init() {
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
setLayout(new BorderLayout());
add(display0);
}
});
} catch (InvocationTargetException e) {
e.printStackTrace();
e.getCause();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void start() {
display0.start();
}
public void stop() {
display0.stop();
}
}
If there's any other piece of code you need from me, just ask and I will post.
Need an answer sooner rather than later, too:p
Thanks all!
If you compiled you applet with jdk 1.6 you must use jre 6 for browser.
Related
In a JavaFX application's init() method I am doing some checks, one of them is a check to see if it can connect to a web address based using Http response codes. This app also has a preloader that runs while these checks are happening.
Depending on the response code, I want it to display an alert window during the preloader application's lifecycle
I am not sure if this is possible using the current javafx preloader class, but is there any workarround that could achieve this?
below is an SSCCE of what I would want
The Application
public class MainApplicationLauncher extends Application implements Initializable{
...
public void init() throws Exception {
for (int i = 1; i <= COUNT_LIMIT; i++) {
double progress =(double) i/10;
System.out.println("progress: " + progress);
notifyPreloader(new ProgressNotification(progress));
Thread.sleep(500);
}
try {
URL url = new URL("https://example.com");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
int code = connection.getResponseCode();
System.out.println("Response code of the object is "+code);
if (code==200) {
System.out.println("Connected to the internet!");
}else if (code==503){
//call the handleConnectionWarning() in preloader
System.out.println("server down !");
}
} catch (UnknownHostException e) {
//call the handleConnectionWarning() in preloader
System.out.println("cannot connect to the internet!");
}
public static void main(String[] args) {
System.setProperty("javafx.preloader", MainPreloader.class.getCanonicalName());
Application.launch(MainApplicationLauncher.class, args);
}
}
The preloader
public class MyPreloader extends Preloader{
...
//Method that should be called from application method
public void handleConnectionWarning() {
Alert alert = new Alert(AlertType.WARNING);
alert.setTitle("Server is Offline");
alert.setHeaderText("Cannot connect to service");
alert.setContentText("Please check your connection");
alert.showAndWait();
}
}
Are there any ways to do this?
Preloader
If you want to continue using Preloader for your splash screen, then you can call the desired method via a notification. Create your own notification class:
// You can modify this class to carry information to the Preloader, such
// as a message indicating what kind of failure occurred.
public class ConnectionFailedNotification implements Preloader.PreloaderNotification {}
Send it to your Preloader:
notifyPreloader(new ConnectionFailedNotification());
And handle it in said Preloader:
#Override
public void handleApplicationNotification(PreloaderNotification info) {
if (info instanceof ConnectionFailedNotification) {
handleConnectionWarning();
}
// ...
}
No Preloader
The Preloader class makes more sense when you're deploying your application via Java Web Start (i.e., to web browsers), where the code has to be downloaded before it can be used. But Java Web Start is no longer supported (though I think there may be a third-party maintaining something at least similar). Given your application is likely targeted for a simple desktop deployment, using Preloader can make things unnecessarily complicated. Instead consider simply updating the primary stage's content after initialization.
Move your init() stuff into a Task implementation:
import java.io.IOException;
import javafx.concurrent.Task;
public class InitTask extends Task<Void> {
private static final int COUNT_LIMIT = 10;
private final boolean shouldSucceed;
public InitTask(boolean shouldSucceed) {
this.shouldSucceed = shouldSucceed;
}
#Override
protected Void call() throws Exception {
for (int i = 1; i <= COUNT_LIMIT; i++) {
updateProgress(i, COUNT_LIMIT);
Thread.sleep(500);
}
// could use a Boolean return type for this, but your real code seems
// more complicated than a simple "yes" / "no" response. If you do
// change the implementation to use a return value, note that you would
// then need to check that return value in the 'onSucceeded' handler
if (!shouldSucceed) {
throw new IOException("service unavailable"); // failure
}
return null; // success
}
}
And then launch that task on a background thread:
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressBar;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;;
public class App extends Application {
#Override
public void start(Stage primaryStage) throws Exception {
var task = new InitTask(false); // change to 'true' to simulate success
task.setOnSucceeded(e -> primaryStage.getScene().setRoot(createMainScreen()));
task.setOnFailed(e -> {
var alert = new Alert(AlertType.WARNING);
alert.initOwner(primaryStage);
alert.setTitle("Server Offline");
alert.setHeaderText("Cannot connect to service");
alert.setContentText("Please check your connection");
alert.showAndWait();
Platform.exit();
});
// Also see the java.util.concurrent.Executor framework
var thread = new Thread(task, "init-thread");
thread.setDaemon(true);
thread.start();
var scene = new Scene(createSplashScreen(task), 600, 400);
primaryStage.setScene(scene);
primaryStage.show();
}
private StackPane createSplashScreen(InitTask task) {
var bar = new ProgressBar();
bar.progressProperty().bind(task.progressProperty());
return new StackPane(bar);
}
private StackPane createMainScreen() {
return new StackPane(new Label("Hello, World!"));
}
}
Side Notes
Your Application subclass should not implement Initializable. That subclass represents the entire application and should never be used as an FXML controller.
I would like to display a progress bar when running a custom IntentionAction in my custom IntellIJ IDEA plugin.
However, it is not displayed no matter what I do. To test whether the problem lies in the IntentionAction, I copy-paste the code to a simple implementation of an AnAction. The whole class looks like so:
public class HelloAction extends AnAction {
public HelloAction() {
super("Hello");
}
public void actionPerformed(AnActionEvent event) {
Project project = event.getData(CommonDataKeys.PROJECT);
ProgressManager.getInstance().run(new Task.Modal(project, "daf", false) {
public void run(ProgressIndicator indicator) {
indicator.setText("This is how you update the indicator");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {}
indicator.setFraction(0.5); // halfway done
try {
Thread.sleep(2000);
} catch (InterruptedException e) {}
}
});
Messages.showMessageDialog(project, "Hello world!", "Greeting", Messages.getInformationIcon());
}
}
And it works perfectly. And when I use the same code inside an IntentionAction, nothing is displayed.
public class GenerateIntentionAction extends PsiElementBaseIntentionAction implements IntentionAction {
...
public void invoke(#NotNull Project project, Editor editor, #NotNull PsiElement element) throws IncorrectOperationException {
ProgressManager.getInstance().run(new Task.Modal(project, "daf", false) {
public void run(ProgressIndicator indicator) {
indicator.setText("This is how you update the indicator");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {}
indicator.setFraction(0.5); // halfway done
try {
Thread.sleep(2000);
} catch (InterruptedException e) {}
}
});
I tried to run call runWithProgressSynchronously instead of run, tried making Task Modal and Backgroundable - to no avail. I do not know what is wrong besides the fact that ProgressIndicator inside IntentionAction is always an EmptyProgressIndicator
If your intention action is invoked inside WriteAction, you can't show modal UI from there. Overriding startInWriteAction and returning false might help.
I'm cutting my teeth on some Java/JavaScript coding and I seem to have hit a wall. I'm trying to pass agruments from Java to JavaScript but no matter what I do "JSObject jso = JSObject.getWindow(this);" always throws an exception. I've done some searching and can't find any solutions. I stole the code below from a website (http://www.codejava.net/java-se/applet/liveconnect-the-api-for-communication-between-java-applet-and-javascript) and don't see any errors in either the JavaScript or the Java and both files compile correctly.
I've added plugin.jar to by buildpath and made sure that the jfxrt.jar is not in the build path. I thought something could possibly be wrong with the plugin.jar in jre7 so I tried jre6 but was getting the same error. The code I'm using is as follows.
Java Code:
package test;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import netscape.javascript.*;
public class TestApplet extends JApplet {
private JButton button = new JButton("Call Javascript");
private JLabel label = new JLabel();
public void init() {
getContentPane().setLayout(new BorderLayout());
getContentPane().add(button, BorderLayout.NORTH);
getContentPane().add(label, BorderLayout.SOUTH);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
Thread runner = new Thread(new Runnable() {
public void run() {
try {
testLiveConnect();
} catch (JSException jse) {
// Error
jse.printStackTrace();
}
}
});
runner.start();
}
});
}
private void testLiveConnect() throws JSException {
JSObject jso = JSObject.getWindow(this);
// call Javascript's method foo() with no argument
String result = (String) jso.call("foo", null);
label.setText(result);
// delay 2 seconds to see the result
try { Thread.sleep(2000); } catch (InterruptedException ie) {};
// call Javascript's method foo() with two arguments
result = (String) jso.call("bar", new String[] {"Alice", "Alisa"});
label.setText(result);
try { Thread.sleep(2000); } catch (InterruptedException ie) {};
// execute a Javascript expression
String expression = "alert('Hi, I am from Javascript.');";
jso.eval(expression);
try { Thread.sleep(2000); } catch (InterruptedException ie) {};
// get value of a named member from Javascript
result = (String) jso.getMember("coop");
label.setText(result);
try { Thread.sleep(2000); } catch (InterruptedException ie) {};
// get value of an indexed member from Javascript
result = (String) jso.getSlot(1);
label.setText(result);
}
}
JavaScript Code:
<html>
<head>
<title>LiveConnect - Java-Javascript communnication demo</title>
</head>
<body>
<center>
<applet id="testApplet"
code="TestApplet.class"
width="200" height="80"
>
</applet>
</center>
</body>
<script type="text/javascript">
var coop = "Ooops!";
this[1] = "Slot 1";
function foo() {
return "This is from foo()";
}
function bar(firstName, lastName) {
return "Greeting " + firstName + " " + lastName + "!";
}
</script>
</html>
Exception Thrown:
netscape.javascript.JSException
at netscape.javascript.JSObject.getWindow(Unknown Source)
at test.TestApplet.testLiveConnect(TestApplet.java:34)
at test.TestApplet.access$0(TestApplet.java:33)
at test.TestApplet$1$1.run(TestApplet.java:22)
at java.lang.Thread.run(Unknown Source)
This drove me nuts once upon a time. Java7 apparently comes with 2 jars that include different implementations of this same class. jfxrt.jar and plugin.jar
I solved issues with these by simply removing jfxrt.jar from my classpath. You'll have to dig for how to do that for your build system. In Intellij, you can go to:
File -> Project Structure -> SDKs
Then, on the classpath tab, highlight jfxrt.jar and click '-'
ETA: I found the answer that originally helped me that has a bit more info: https://stackoverflow.com/a/14156602/1057157
I had the same problem and solved it simply by changing the following line:
JSObject jso = JSObject.getWindow(this);
to:
JSObject jso = JSObject.getWindow((Applet)this);
import org.newdawn.slick.Image;
import org.newdawn.slick.SlickException;
public class Images {
try {
public static Image button = new Image("images/buttons/0/Button.png");
} catch(SlickException e) {
e.printStackTrace();
}
}
This just gives an error, I want to be able to store some images in static variables and access them from another class without instantiating it.
I could possibly make a method to initialise all them and set values to them, but then the variables wouldn't be static.
The reason I need TryCatch is because the constructor of the Image class throws a SlickException
Two options:
Use a static initializer block
public static final Image button;
static {
try/catch in here, assign to button
}
Use a method for initialization
public static final Image button = createButton();
private static Image createButton() {
try/catch in here
}
Personally I'm somewhat skeptical of this being a good idea though - making type initialization do "real work" can lead to bugs which are hard to track down. Is all the referring code really set up for it to be null in the case of problems?
You can put your exception handling code in a static block.
public static Image button;
static {
try {
button = new Image("images/buttons/0/Button.png");
} catch(SlickException e) {
e.printStackTrace();
}
}
Just declare the static variable outside the block..and it will work..
public static final Image button = setImageButt();
public static Image setImageButt(){
try {
button = new Image("images/buttons/0/Button.png");
} catch(SlickException e) {
e.printStackTrace();
}
}
try to place it into a static block
public static Image button;
static{
try {
button = new Image("images/buttons/0/Button.png");
} catch(SlickException e) {
e.printStackTrace();
}
}
You should use static constructor.
public class Images {
public static Image button;
static{
try {
button = new Image("images/buttons/0/Button.png");
} catch(SlickException e) {
e.printStackTrace();
}
}
}
Use a static block for initialization and take extra care to not swallow the exception:
public class Images {
public final static Image BUTTON;
static {
Image i;
try {
i = new Image("images/buttons/0/Button.png");
} catch (SlickException e) {
throw new ExceptionInInitializerError(e);
}
BUTTON = i;
}
}
I corrected some things from your code:
Creating the image in initializer implies it should be a constant, thus final.
Constants should have uppercase names, thus BUTTON.
Exceptions during initialization should not be swallowed but properly indicated. Otherwise you can spend hours debugging the image not being found because there will be no indication initialization failed. ExceptionInInitializerError is the standard exception to throw in that case.
There are other solutions, but this is the cleanest IMO.
I have faced similar problem once and while for finding the solution I just came across to this question. I have solved similar problem just putting all of the code in the default constructor.
Your solution code will be like this:
import org.newdawn.slick.Image;
import org.newdawn.slick.SlickException;
public class Images {
public Images{
try {
public static Image button = new Image("images/buttons/0/Button.png");
} catch(SlickException e) {
e.printStackTrace();
}
}
}
I am wondering if it is possible to embed Firefox browser as a component in a Java Swing based application.
I have done a bit of research from the Internet, but I could not find an answer. Some people suggest to use other browser component available in Java. I do not think that is preferable, as the rendering engine would be different to Firefox.
Any idea? Many thanks.
Absolutely I have done it before please check out the Mozilla Embedding for Java
Here is some sample code
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileNotFoundException;
import java.io.File;
import javax.swing.*;
import org.mozilla.xpcom.*;
import org.mozilla.interfaces.*;
/*
Websites ref
http://groups.google.com/group/mozilla.dev.tech.java/browse_thread/thread/898ba6751d0c57f7
http://skrul.com/blog/code/
http://wirestorm.net/blog/?cat=9
*/
public class BrowserTest implements nsIWebProgressListener,nsIWeakReference, nsIInterfaceRequestor, nsIWebBrowserChrome, nsISHistoryListener{
static {
try {
System.loadLibrary("NativeWindow");
} catch (UnsatisfiedLinkError e) {
System.err.println("can't find your library");
}
}
private static final String frameTitle="GRE Embedded";
public static void main(String[] args) {
BrowserConroller controler=new BrowserConroller();
controler.run();
new BrowserTest().start();
}
public void start(){
JFrame f = new JFrame( frameTitle );
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(400, 150);
Container content = f.getContentPane();
content.setBackground(Color.white);
content.setLayout(new FlowLayout());
content.add(new JLabel("Initializing ... "));
f.setVisible(true);
File grePath = null;
LocationProvider locProvider;
Mozilla mozilla = Mozilla.getInstance();
GREVersionRange[] range = new GREVersionRange[1];
range[0] = new GREVersionRange("1.8.0", true, "1.9", false);
try {
grePath = Mozilla.getGREPathWithProperties(range, null);
mozilla.initialize(grePath);
locProvider = new LocationProvider(grePath);
mozilla.initEmbedding(grePath, grePath, locProvider);
}
catch (FileNotFoundException e) {
System.out.println("Error: FileNotFoundException");
}
catch (XPCOMException e) {
System.out.println("Error: XPCOMException");
}
//---------- END GRE INITIALIZATION------------
nsIServiceManager serviceManager = mozilla.getServiceManager();
nsIAppStartup appStartup = (nsIAppStartup)serviceManager.getServiceByContractID("#mozilla.org/toolkit/app-startup;1", nsIAppStartup.NS_IAPPSTARTUP_IID);
nsIWindowCreator windowCreator = (nsIWindowCreator)appStartup.queryInterface(nsIWindowCreator.NS_IWINDOWCREATOR_IID);
nsIWindowWatcher windowWatcher =(nsIWindowWatcher)serviceManager.getServiceByContractID("#mozilla.org/embedcomp/window-watcher;1",nsIWindowWatcher.NS_IWINDOWWATCHER_IID);
windowWatcher.setWindowCreator(windowCreator);
nsIDOMWindow win = windowWatcher.openWindow(null, "http://google.com", "MAIN_WIN","chrome,resizable,centerscreen", null);
windowWatcher.setActiveWindow( win );
nsIComponentManager componentManager = mozilla.getComponentManager();
String NS_IWEBBROWSER_CID = "F1EAC761-87E9-11d3-AF80-00A024FFC08C"; //$NON-NLS-1$
nsIWebBrowser webBrowser = (nsIWebBrowser) componentManager.createInstance(NS_IWEBBROWSER_CID, null, nsIWebBrowser.NS_IWEBBROWSER_IID);
webBrowser.setContainerWindow(this);
webBrowser.addWebBrowserListener(this, nsIWebProgressListener.NS_IWEBPROGRESSLISTENER_IID);
// nsIWebNavigation webNavigation=(nsIWebNavigation)webBrowser.queryInterface(nsIWebNavigation.NS_IWEBNAVIGATION_IID);
// webNavigation.loadURI("http://www.zdnet.com", nsIWebNavigation.LOAD_FLAGS_NONE, null, null, null);
//
nsIBaseWindow baseWindow = (nsIBaseWindow) webBrowser.queryInterface(nsIBaseWindow.NS_IBASEWINDOW_IID);
long handle=FindWindow.getHWND( frameTitle );
baseWindow.initWindow(handle, 0, 0, 0,350,350);
baseWindow.create();
baseWindow.setVisibility(true);
//
// nsIDOMWindow domWin=webBrowser.getContentDOMWindow();
// nsIDOMEventTarget domEventTarget= (nsIDOMEventTarget)domWin.queryInterface(nsIDOMEventTarget.NS_IDOMEVENTTARGET_IID);
// domEventTarget.addEventListener("click", new EventListener(), false);
//
//Hide JFrame after it have been initialized
f.setVisible(true);
//
// nsIWebNavigation webNavigation=(nsIWebNavigation)webBrowser.queryInterface(nsIWebNavigation.NS_IWEBNAVIGATION_IID);
// webNavigation.loadURI("http://www.zdnet.com", nsIWebNavigation.LOAD_FLAGS_NONE, null, null, null);
//
appStartup.run();
System.out.println("try termEmbedding");
try {
System.out.println("mozilla.termEmbedding(); START");
mozilla.termEmbedding();
System.out.println("mozilla.termEmbedding(); FINISHED");
}
catch (XPCOMException e) {
System.out.println("Fehler: XPCOMException");
}
System.out.println("finished termEmbedding");
System.out.println("All done");
}
public void onLocationChange(nsIWebProgress webProgress, nsIRequest request, nsIURI location) {
c("onLocationChange");
}
public void onProgressChange(nsIWebProgress webProgress, nsIRequest request, int curSelfProgress, int maxSelfProgress, int curTotalProgress, int maxTotalProgress) {
c("onProgressChange");
}
public void onSecurityChange(nsIWebProgress webProgress, nsIRequest request, long state) {
c("onSecurityChange");
}
public void onStateChange(nsIWebProgress webProgress, nsIRequest request, long stateFlags, long status) {
c("onStateChange");
}
public void onStatusChange(nsIWebProgress webProgress, nsIRequest request, long status, String message) {
c("onStatusChange");
}
public nsISupports queryInterface(String uuid) {
c("queryInterface");
return null;
}
public nsISupports queryReferent(String uuid) {
c("queryReferent");
return null;
}
public nsISupports getInterface(String uuid) {
c("getInterface");
return null;
}
private void c(Object o){
System.out.println(o);
}
public void destroyBrowserWindow() {
c("destroyBrowserWindow");
}
public void exitModalEventLoop(long status) {
c("exitModalEventLoop");
}
public long getChromeFlags() {
c("getChromeFlags");
return 0;
}
public nsIWebBrowser getWebBrowser() {
c("getWebBrowser");
return null;
}
public boolean isWindowModal() {
c("isWindowModal");
return false;
}
public void setChromeFlags(long chromeFlags) {
c("setChromeFlags");
}
public void setStatus(long statusType, String status) {
c("setStatus");
}
public void setWebBrowser(nsIWebBrowser webBrowser) {
c("setWebBrowser");
}
public void showAsModal() {
c("showAsModal");
}
public void sizeBrowserTo(int acx, int acy) {
c("sizeBrowserTo");
}
public boolean onHistoryGoBack(nsIURI backURI) {
c("onHistoryGoBack");
return false;
}
public boolean onHistoryGoForward(nsIURI forwardURI) {
c("onHistoryGoForward");
return false;
}
public boolean onHistoryGotoIndex(int index, nsIURI gotoURI) {
c(" onHistoryGotoIndex");
return false;
}
public void onHistoryNewEntry(nsIURI newURI) {
c(" onHistoryNewEntry");
}
public boolean onHistoryPurge(int numEntries) {
c(" onHistoryPurge");
return false;
}
public boolean onHistoryReload(nsIURI reloadURI, long reloadFlags) {
c(" onHistoryReload");
return false;
}
} //public class JavaXPCOM_test1[/code]
As answered here (Best Java/Swing browser component?) - and from my own testing - djproject seems to be the best.
It has last been updated March 2009 and some demo links are broken.. so the project seems not to be too active right now.. Still: When I needed it in 2010 it was awesome.
A quick Google search returns a product called JxBrowser that does this.
However, I would question whether you really need a full blown browser component like Firefox in your application. What do you need it for in your application?
How about embedding your GUI inside the browser instead, with an applet, GWT or another rich client approach?
Not directly. You could port your UI (or at least part of it) to SWT and then use the Browser component (see this FAQ item).
If you can't port your UI to SWT, then you can embed your Swing UI in SWT (SWT Shell == Swing JFrame). But there will be some pain ahead.
Update: Firefox is no longer supported by SWT. Currently supported is the system's default browser or WebKit (see https://github.com/eclipse/eclipse.platform.swt/search?q=BrowserFactory&unscoped_q=BrowserFactory).