Java调用JavaScript示例

 

/**   
 * 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.properties
 
yellowButton.action=panel.background = java.awt.Color.YELLOW
blueButton.action=panel.background = java.awt.Color.BLUE
redButton.action=panel.background = java.awt.Color.RED
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值