Bas*_*que 24
所述书Vaadin包括上推的一章,包括使用一个例子Vaadin图表.
以下是我的代码.虽然基于上面提到的Vaadin Charts示例,但我通过将Chart对象的使用替换为简单Label对象来简化它.标签每秒钟更新一次,以告诉您当前时间.

警告:我的下面的例子是为了简单而构建的,不是作为生产代码.睡眠线程是管理预定线程工作的原始和笨拙方式.Java Executor为这种工作提供了便利.在实际项目中,我将使用ScheduledExecutorService而不是单个睡眠Thread对象来安排我们的任务(告知时间).相关提示:切勿Timer在Servlet环境中使用.有关更全面,更真实的示例,请参阅我对与Vaadin推送类似问题的回答.
我在这个例子中采用了其他快捷方式,例如:我将Label小部件直接放在UI实际工作中使用a Layout来包含Label.
我的代码在NetBeans 8.0.2中使用Vaadin 7.3.7和Java 8 Update 25,在Mac OS X 10.8.5(Mountain Lion)上使用Tomcat 8.0.15.
推送技术相对较新,尤其是WebSocket的多样性.请务必使用最新版本的Web服务器,例如Tomcat 7或8的最新更新.
此代码是单个文件,即MyUI.java文件.要使用此代码:
MyUI下面的代码替换类的内容.@Push 注解除了中间的代码,请注意我们如何将@Push注释添加到MyUI类定义中.
package com.example.pushvaadinapp;
import com.vaadin.annotations.Push;
import com.vaadin.annotations.Theme;
import com.vaadin.annotations.VaadinServletConfiguration;
import com.vaadin.annotations.Widgetset;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinServlet;
import com.vaadin.ui.Label;
import com.vaadin.ui.UI;
import javax.servlet.annotation.WebServlet;
/**
* © 2014 Basil Bourque. This source code may be used freely forever by anyone absolving me of any and all responsibility.
*
* +----------------------------+
* | NOT FOR PRODUCTION USE! |
* +----------------------------+
* Sleeping threads is an awkward way to manage scheduled background work.
* By the way, never use a 'Timer' in a Servlet environment.
* Use an Executor instead, probably a ScheduledExecutorService.
*/
@Push
@Theme ( "mytheme" )
@Widgetset ( "com.example.pushvaadinapp.MyAppWidgetset" )
public class MyUI extends UI
{
Label label = new Label( "Now : " );
@Override
protected void init ( VaadinRequest vaadinRequest )
{
// Put a widget on this UI. In real work we would use a Layout.
setContent( this.label );
// Start the data feed thread
new FeederThread().start();
}
@WebServlet ( urlPatterns = "/*" , name = "MyUIServlet" , asyncSupported = true )
@VaadinServletConfiguration ( ui = MyUI.class , productionMode = false )
public static class MyUIServlet extends VaadinServlet
{
}
public void tellTime ()
{
label.setValue( "Now : " + new java.util.Date() ); // If Java 8, use: Instant.now(). Or, in Joda-Time: DateTime.now().
}
class FeederThread extends Thread
{
int count = 0;
@Override
public void run ()
{
try {
// Update the data for a while
while ( count < 100 ) {
Thread.sleep( 1000 );
// Calling special 'access' method on UI object, for inter-thread communication.
access( new Runnable()
{
@Override
public void run ()
{
count ++;
tellTime();
}
} );
}
// Inform that we have stopped running
// Calling special 'access' method on UI object, for inter-thread communication.
access( new Runnable()
{
@Override
public void run ()
{
label.setValue( "Done." );
}
} );
} catch ( InterruptedException e ) {
e.printStackTrace();
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8790 次 |
| 最近记录: |