java : mozilla rhino js引擎 使用教程

https://mozilla.github.io/rhino/ 下载 rhino1_7R5.zip , 解压后运行 cmd

cd D:\rhino\rhino1_7R5

先测试最简单的: java -jar js.jar swing1.js

var SwingGui = new JavaImporter(javax.swing, javax.swing.event, javax.swing.border, java.awt.event); 
with (SwingGui) { 
	var frame = new JFrame("test");
	frame.setSize(300,200);
	var pane = frame.getContentPane();
	var button1 = new JButton("button1"); 
	pane.add(button1);
    frame.setVisible(true);	
	frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

测试发行版中例子: java -jar js.jar examples/SwingApplication.js 居然报错了

js: Cannot convert function to interface java.awt.event.WindowListener since it
contains methods with different names

看了书【Java 程序设计】,明白了,改一处即可。

with (swingNames) {
    try {
	UIManager.
            setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
    } catch (e) { }

    //Create the top-level container and add contents to it.
    var frame = new swingNames.JFrame("SwingApplication");
    frame.getContentPane().add(createComponents(), BorderLayout.CENTER);

    // Pass JS function as implementation of WindowListener. It is allowed since 
    // all methods in WindowListener have the same signature. To distinguish 
    // between methods Rhino passes to JS function the name of corresponding 
    // method as the last argument 
/*
    frame.addWindowListener(function(event, methodName) {
	if (methodName == "windowClosing") {     
            java.lang.System.exit(0);
	}
    });
*/
    //Finish setting up the frame, and show it.
    frame.pack();
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

一个较复杂的例子: 来自参考书【JavaScript 权威指南】第12章

java -jar js.jar  rhinoURLFetcher.js

/*
 * A download manager application with a simple Java GUI
 */
var swingNames = new JavaImporter(javax.swing, javax.swing.event, javax.swing.border, java.awt,java.awt.event); 

importClass(java.net.URL);
importClass(java.io.FileOutputStream);
importClass(java.lang.Thread);

with (swingNames) {
var frame = new JFrame("Rhino URL Fetcher");     // The application window
var urlfield = new JTextField(30);               // URL entry field
var button = new JButton("Download");            // Button to start download
var filechooser = new JFileChooser();            // A file selection dialog
var row = Box.createHorizontalBox();             // A box for field and button
var col = Box.createVerticalBox();               // For the row & progress bars
var padding = new EmptyBorder(3,3,3,3);          // Padding for rows

// Put them all together and display the GUI
row.add(urlfield);                               // Input field goes in the row
row.add(button);                                 // Button goes in the row
col.add(row);                                    // Row goes in the column
frame.add(col);                                  // Column goes in the frame
row.setBorder(padding);                          // Add some padding to the row
frame.pack();                                    // Set to minimum size
frame.visible = true;                            // Make the window visible
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// When the user clicks the button, call this function
button.addActionListener(function() {
    try {
        // Create a java.net.URL to represent the source URL.
        // (This will check that the user's input is well-formed)
        var url = new URL(urlfield.text);
        // Ask the user to select a file to save the URL contents to.
        var response = filechooser.showSaveDialog(frame);
        // Quit now if they clicked Cancel
        if (response != JFileChooser.APPROVE_OPTION) return;
        // Otherwise, get the java.io.File that represents the destination file
        var file = filechooser.getSelectedFile();
        // Now start a new thread to download the url
        new java.lang.Thread(function() { download(url,file); }).start();
    }    catch(e) {
        // Display a dialog box if anything goes wrong
        JOptionPane.showMessageDialog(frame, e.message, "Exception",
                                     JOptionPane.ERROR_MESSAGE);
    }
});

// Use java.net.URL, etc. to download the content of the URL and use
// java.io.File, etc. to save that content to a file.  Display download
// progress in a JProgressBar component.  This will be invoked in a new thread.
function download(url, file) {
    try {
        // Each time we download a URL we add a new row to the window
        // to display the url, the filename, and the download progress
        var row = Box.createHorizontalBox();     // Create the row
        row.setBorder(padding);                  // Give it some padding
        var label = url.toString() + ": ";       // Display the URL 
        row.add(new JLabel(label));              //   in a JLabel
        var bar = new JProgressBar(0, 100);      // Add a progress bar
        bar.stringPainted = true;                // Display filename in
        bar.string = file.toString();            //   the progress bar
        row.add(bar);                            // Add bar to this new row
        col.add(row);                            // Add row to the column
        frame.pack();                            // Resize window

        // We don't yet know the URL size, so bar starts just animating
        bar.indeterminate = true; 

        // Now connect to the server and get the URL length if we can
        var conn = url.openConnection();         // Get java.net.URLConnection
        conn.connect();                          // Connect and wait for headers
        var len = conn.contentLength;            // See if we have URL length
        if (len) {                               // If length known, then 
            bar.maximum = len;                   //   set the bar to display 
            bar.indeterminate = false;           //   the percent downloaded
        }

        // Get input and output streams
        var input = conn.inputStream;            // To read bytes from server
        var output = new FileOutputStream(file); // To write bytes to file
        
        // Create an array of 4k bytes as an input buffer
        var buffer = java.lang.reflect.Array.newInstance(java.lang.Byte.TYPE,
                                                         4096);
        var num;
        while((num=input.read(buffer)) != -1) {  // Read and loop until EOF
            output.write(buffer, 0, num);        // Write bytes to file
            bar.value += num;                    // Update progress bar
        }
        output.close();                          // Close streams when done
        input.close();
    }
    catch(e) { // If anything goes wrong, display error in progress bar
        if (bar) {
            bar.indeterminate = false;           // Stop animating
            bar.string = e.toString();           // Replace filename with error
        }
    }
}
}

cd D:\rhino\rhino1_7R5\examples
java -cp ..\js.jar;. org.mozilla.javascript.tools.shell.Main unique.js test1.txt
编写 rhino.bat

@echo off
java -cp D:/rhino/rhino1_7R5/js.jar;. org.mozilla.javascript.tools.shell.Main %*

rhino.bat swing1.js

rhino.bat  rhinoURLFetcher.js

猜你喜欢

转载自blog.csdn.net/belldeep/article/details/81811554