Java调用JavaScript示例

作者: admin 分类: 学习文档 发布时间: 2011-11-07 17:17
Java代码
  1. /**
  2. * ScriptTest
  3. * java调用javascript示例代码
  4. * @author your name
  5. * Date: Nov 4, 2011
  6. */
  7. package org.sun.script.js;
  8. import java.awt.Component;
  9. import java.awt.Container;
  10. import java.awt.EventQueue;
  11. import java.beans.EventSetDescriptor;
  12. import java.beans.IntrospectionException;
  13. import java.beans.Introspector;
  14. import java.io.FileReader;
  15. import java.lang.reflect.InvocationHandler;
  16. import java.lang.reflect.InvocationTargetException;
  17. import java.lang.reflect.Method;
  18. import java.lang.reflect.Proxy;
  19. import java.util.Properties;
  20. import javax.script.ScriptEngine;
  21. import javax.script.ScriptEngineFactory;
  22. import javax.script.ScriptEngineManager;
  23. import javax.swing.JButton;
  24. import javax.swing.JFrame;
  25. import javax.swing.JPanel;
  26. public class ScriptTest
  27. {
  28. public static void main(final String[] args)
  29. {
  30. EventQueue.invokeLater(new Runnable()
  31. {
  32. public void run()
  33. {
  34. String language;
  35. if (args.length == 0)
  36. language = “js”;
  37. else
  38. language = args[0];
  39. ScriptEngineManager manager = new ScriptEngineManager();
  40. System.out.println(“Available factories: “);
  41. for (ScriptEngineFactory factory : manager.getEngineFactories())
  42. System.out.println(factory.getEngineName());
  43. final ScriptEngine engine = manager.getEngineByName(language);
  44. if (engine == null)
  45. {
  46. System.err.println(“No engine for ” + language);
  47. System.exit(1);
  48. }
  49. ButtonFrame frame = new ButtonFrame();
  50. try
  51. {
  52. // File initFile = new File(“init.” + language);
  53. // if (initFile.exists())
  54. // {
  55. // System.out.println(“exists”);
  56. // engine.eval(new FileReader(initFile));
  57. // }
  58. getComponentBindings(frame, engine);
  59. final Properties events = new Properties();
  60. events.load(new FileReader(“bin\org\sun\script\js\” + language + “.properties”));
  61. for (final Object e : events.keySet())
  62. {
  63. String[] s = ((String) e).split(“\.”);
  64. addListener(s[0], s[1], (String) events.get(e), engine);
  65. }
  66. }
  67. catch (Exception e)
  68. {
  69. e.printStackTrace();
  70. }
  71. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  72. frame.setTitle(“ScriptTest”);
  73. frame.setVisible(true);
  74. }
  75. });
  76. }
  77. /**
  78. * Gathers all named components in a container.
  79. *
  80. * @param c the component
  81. * @param namedComponents
  82. */
  83. private static void getComponentBindings(Component c, ScriptEngine engine)
  84. {
  85. String name = c.getName();
  86. if (name != null)
  87. engine.put(name, c);
  88. if (c instanceof Container)
  89. {
  90. for (Component child : ((Container) c).getComponents())
  91. getComponentBindings(child, engine);
  92. }
  93. }
  94. /**
  95. * Adds a listener to an object whose listener method executes a script.
  96. *
  97. * @param beanName the name of the bean to which the listener should be
  98. * added
  99. * @param eventName the name of the listener type, such as “action” or
  100. * “change”
  101. * @param scriptCode the script code to be executed
  102. * @param engine the engine that executes the code
  103. * @param bindings the bindings for the execution
  104. */
  105. private static void addListener(String beanName, String eventName, final String scriptCode,
  106. final ScriptEngine engine) throws IllegalArgumentException, IntrospectionException, IllegalAccessException,
  107. InvocationTargetException
  108. {
  109. Object bean = engine.get(beanName);
  110. EventSetDescriptor descriptor = getEventSetDescriptor(bean, eventName);
  111. if (descriptor == null)
  112. return;
  113. descriptor.getAddListenerMethod().invoke(bean,
  114. Proxy.newProxyInstance(null, new Class[] { descriptor.getListenerType() }, new InvocationHandler()
  115. {
  116. public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
  117. {
  118. engine.eval(scriptCode);
  119. return null;
  120. }
  121. }));
  122. }
  123. private static EventSetDescriptor getEventSetDescriptor(Object bean, String eventName)
  124. throws IntrospectionException
  125. {
  126. for (EventSetDescriptor descriptor : Introspector.getBeanInfo(bean.getClass()).getEventSetDescriptors())
  127. if (descriptor.getName().equals(eventName))
  128. return descriptor;
  129. return null;
  130. }
  131. }
  132. class ButtonFrame extends JFrame
  133. {
  134. public ButtonFrame()
  135. {
  136. setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
  137. panel = new JPanel();
  138. panel.setName(“panel”);
  139. add(panel);
  140. yellowButton = new JButton(“Yellow”);
  141. yellowButton.setName(“yellowButton”);
  142. blueButton = new JButton(“Blue”);
  143. blueButton.setName(“blueButton”);
  144. redButton = new JButton(“Red”);
  145. redButton.setName(“redButton”);
  146. panel.add(yellowButton);
  147. panel.add(blueButton);
  148. panel.add(redButton);
  149. }
  150. public static final int DEFAULT_WIDTH = 300;
  151. public static final int DEFAULT_HEIGHT = 200;
  152. private JPanel panel;
  153. private JButton yellowButton;
  154. private JButton blueButton;
  155. private JButton redButton;
  156. }
/**   
 * ScriptTest
 *  java调用javascript示例代码
 * @author  your name
 * Date: Nov 4, 2011
 */
package org.sun.script.js;

import java.awt.Component;
import java.awt.Container;
import java.awt.EventQueue;
import java.beans.EventSetDescriptor;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.io.FileReader;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Properties;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineFactory;
import javax.script.ScriptEngineManager;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class ScriptTest
{

    public static void main(final String[] args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                String language;
                if (args.length == 0)
                    language = "js";
                else
                    language = args[0];

                ScriptEngineManager manager = new ScriptEngineManager();
                System.out.println("Available factories: ");
                for (ScriptEngineFactory factory : manager.getEngineFactories())
                    System.out.println(factory.getEngineName());
                final ScriptEngine engine = manager.getEngineByName(language);

                if (engine == null)
                {
                    System.err.println("No engine for " + language);
                    System.exit(1);
                }

                ButtonFrame frame = new ButtonFrame();

                try
                {
                    // File initFile = new File("init." + language);
                    // if (initFile.exists())
                    // {
                    // System.out.println("exists");
                    // engine.eval(new FileReader(initFile));
                    // }

                    getComponentBindings(frame, engine);

                    final Properties events = new Properties();
                    events.load(new FileReader("bin\org\sun\script\js\" + language + ".properties"));
                    for (final Object e : events.keySet())
                    {
                        String[] s = ((String) e).split("\.");
                        addListener(s[0], s[1], (String) events.get(e), engine);
                    }
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }

                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setTitle("ScriptTest");
                frame.setVisible(true);
            }
        });
    }

    /**
     * Gathers all named components in a container.
     * 
     * @param c the component
     * @param namedComponents
     */
    private static void getComponentBindings(Component c, ScriptEngine engine)
    {
        String name = c.getName();
        if (name != null)
            engine.put(name, c);
        if (c instanceof Container)
        {
            for (Component child : ((Container) c).getComponents())
                getComponentBindings(child, engine);
        }
    }

    /**
     * Adds a listener to an object whose listener method executes a script.
     * 
     * @param beanName the name of the bean to which the listener should be
     *            added
     * @param eventName the name of the listener type, such as "action" or
     *            "change"
     * @param scriptCode the script code to be executed
     * @param engine the engine that executes the code
     * @param bindings the bindings for the execution
     */
    private static void addListener(String beanName, String eventName, final String scriptCode,
            final ScriptEngine engine) throws IllegalArgumentException, IntrospectionException, IllegalAccessException,
            InvocationTargetException
    {
        Object bean = engine.get(beanName);
        EventSetDescriptor descriptor = getEventSetDescriptor(bean, eventName);
        if (descriptor == null)
            return;
        descriptor.getAddListenerMethod().invoke(bean,
                Proxy.newProxyInstance(null, new Class[] { descriptor.getListenerType() }, new InvocationHandler()
                {
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
                    {
                        engine.eval(scriptCode);
                        return null;
                    }
                }));

    }

    private static EventSetDescriptor getEventSetDescriptor(Object bean, String eventName)
            throws IntrospectionException
    {
        for (EventSetDescriptor descriptor : Introspector.getBeanInfo(bean.getClass()).getEventSetDescriptors())
            if (descriptor.getName().equals(eventName))
                return descriptor;
        return null;
    }
}

class ButtonFrame extends JFrame
{
    public ButtonFrame()
    {
        setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);

        panel = new JPanel();
        panel.setName("panel");
        add(panel);

        yellowButton = new JButton("Yellow");
        yellowButton.setName("yellowButton");
        blueButton = new JButton("Blue");
        blueButton.setName("blueButton");
        redButton = new JButton("Red");
        redButton.setName("redButton");

        panel.add(yellowButton);
        panel.add(blueButton);
        panel.add(redButton);
    }

    public static final int DEFAULT_WIDTH = 300;
    public static final int DEFAULT_HEIGHT = 200;

    private JPanel panel;
    private JButton yellowButton;
    private JButton blueButton;
    private JButton redButton;
}

 

Js代码
  1. js.properties
js.properties
Js代码
  1. <PRE class=js name=”code”>yellowButton.action=panel.background = java.awt.Color.YELLOW
  2. blueButton.action=panel.background = java.awt.Color.BLUE
  3. redButton.action=panel.background = java.awt.Color.RED</PRE>

如果觉得我的文章对您有用,请随意赞赏。您的支持将鼓励我继续创作!

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

Protected by WP Anti Spam