【问题标题】:How to call codenameone java class method from javascript?如何从javascript调用codenameone java类方法?
【发布时间】:2016-11-11 13:08:25
【问题描述】:

我有一个 codenameone 类,其中包含一个为移动应用上传文件的方法。我想在用户单击该上传按钮时从我的 javascript 函数中调用该 codenameone 类方法。

下面是我要上传文件的代号类方法。

public void actionPerformed1(){ 
    if (FileChooser.isAvailable()) {
        FileChooser.showOpenDialog("image/*", e2-> {
            String file=null;
            if(e2!=null){
                file = (String)e2.getSource();
            }
            if (file == null) {
                hi.revalidate();
            } else {
                String extension = null;
                if (file.lastIndexOf(".") > 0) {
                    extension = file.substring(file.lastIndexOf(".")+1);
                }
                if ("txt".equals(extension)) {
                    FileSystemStorage fs = FileSystemStorage.getInstance();
                    try {
                        InputStream fis = fs.openInputStream(file);
                        hi.addComponent(new SpanLabel(Util.readToString(fis)));
                    } catch (Exception ex) {
                        Log.e(ex);
                    }
                } else {
                    hi.add("Selected file "+file);
                }
            }
            hi.revalidate();
        });
    }

下面是我的 html 文件,我将在其中使用 javascript 调用 codenameone actionPerformed1() 方法。

<pre>
    type="button" value="call method"    
    onClick = "document.FileChooserDemo.actionPerformed1()" 
</pre>

我可以在 javascript 中做什么来调用 codenameone 方法?

谢谢。

【问题讨论】:

  • @Quentin Codename One 不是 Java 小程序。您正在阅读代码颠倒这是一个嵌入式移动应用程序...

标签: javascript codenameone


【解决方案1】:

查看JavaDocs for the javascript package,特别是标题为“从 Javascript 调用 Java 方法”的部分。

JSObject logger = (JSObject)ctx.get("{}");
logger.set("log", new JSFunction(){

    public void apply(JSObject self, Object[] args) {
        String msg = (String)args[0];
        Log.p("[Javascript Logger] "+msg);
    }

});

ctx.set("window.logger", logger);

然后从 JavaScript 这将起作用:

logger.log('This is a test message');

【讨论】:

    猜你喜欢
    • 2015-11-13
    • 1970-01-01
    • 2017-04-10
    • 2018-07-30
    • 2016-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多