Search code examples
javapopupwindownashorn

Call Javascript Popup in java program


I'm try show Popup in java program(web).

I try ScriptEngine with javascript, nashorn but fail. Because alert,confirm, prompt is not method of js.

Code in java program:

ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
engine.eval(new FileReader("script.js"));

Invocable invocable = (Invocable) engine;
invocable.invokeFunction("openPopup", "ABC XYZ");

and in script.js:

function openPopup(str){
    alert(str);
}

Run it, error show:

"alert" is undefined


Solution

  • Explanation

    Opening a JavaScript popup in Java is not possible. The JavaScript Engine Nashorn does not provide this method. It usually is a functionality provided by browsers.

    That is also why you are getting:

    "alert" is undefined


    Solution

    You can open popup windows with different tools in Java, for example Swing or JavaFX. Those are tools with which you can create programs with graphical user interfaces (GUI), i.e. that have windows.

    Here is an official tutorial by Oracle on how to create dialogs with Swing.

    The relevant method for creating just a simple popup is:

    JOptionPane.showMessageDialog(frame, "Hello world!");
    

    Where frame is a reference to the window which should be the parent of this popup. However you can simply pass null for a quick and dirty popup:

    JOptionPane.showMessageDialog(null, "Hello world!");
    

    Just use the above code, import the JOptionPane and it should work:

    import javax.swing.JOptionPane;
    

    The class has more interesting methods to check out, like input dialogs. Here is its documentation.


    The JavaFX solution is a bit more complicated as it requires you to setup the frame and handle several events.

    You may check out this other question SO: Popup window with table view in JavaFX 2.0. It uses the designated class Popup (documentation).