2016-11-10 42 views
1

我有一个codenameone类,其中包含一个上传文件的方法,用于移动应用程序。我想从我的javascript函数中调用codenameone类方法,同时用户单击该上传按钮。如何从javascript调用codenameone java类方法?

下面是我的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方法吗?

谢谢。

+0

@Quentin [代号一(https://www.codenameone.com/)不是一个Java小程序。您正在阅读代码颠倒这是一个嵌入式移动应用程序... –

回答

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');