[英]How do you call Scala objects from Java?
Java code: Java代码:
import javax.swing.Timer;
class Main {
public static void main(String args[]) {
MyListener myListener = new MyListener();
Timer timer = new Timer(1000, myListener);
timer.start();
while(timer.isRunning()) {
System.out.print(".");
}
}
}
Scala code: Scala代码:
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
class MyListener extends ActionListener {
override def actionPerformed(arg0: ActionEvent) {
println("Do something");
}
}
Command line: 命令行:
scalac MyListener.scala
javac Main.java
java -cp /usr/share/java/scala-library.jar:. Main
I'd start by using java.util.Timer - not javax.swing.Timer. 我首先使用java.util.Timer - 而不是javax.swing.Timer。 The swing timer won't work unless you are running your app with a GUI (ie. it won't work if you run it on Linux through a console without a special command line parameter - best avoided). 除非您使用GUI运行应用程序,否则swing计时器将无法工作(即,如果您通过没有特殊命令行参数的控制台在Linux上运行它,它将无法工作 - 最好避免)。
Setting that aside: 把它放在一边:
Be sure, that when you try to run the code, you include scala-library.jar on your classpath. 请确保,当您尝试运行代码时,在类路径中包含scala-library.jar。
Don't forget to start the timer - timer.start() 别忘了启动计时器 - timer.start()
This code worked fine for me (the Scala code required no modification): 这段代码对我来说很好(Scala代码不需要修改):
MyListener myListener = new MyListener();
Timer timer = new Timer(1000, myListener);
timer.start();
Thread.sleep(10000);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.