随笔-57  评论-202  文章-17  trackbacks-0
 
      这个范例说明如何用JFreeChart画简单的柱状图,下面是一个JSP的简单范例:

<%@ page contentType="text/html; charset=GB2312" %>
<%@ page import="java.awt.*, java.text.*, java.util.*" %>
<%@ page import="org.jfree.chart.*" %>
<%@ page import="org.jfree.chart.axis.*" %>
<%@ page import="org.jfree.chart.labels.StandardCategoryItemLabelGenerator" %>
<%@ page import="org.jfree.chart.plot.*" %>
<%@ page import="org.jfree.chart.renderer.*" %>
<%@ page import="org.jfree.chart.servlet.ServletUtilities" %>
<%@ page import="org.jfree.data.DefaultCategoryDataset" %>
<%@ page import="org.jfree.ui.TextAnchor" %>

<%
  
//The data for the bar chart
  double[] data = {85156179.5211123};
  
//The labels for the bar chart
  String[] labels = {"Mon""Tue""Wed""Thu""Fri"};
  
  DefaultCategoryDataset dataset 
= new DefaultCategoryDataset();
  
for (int i = 0; i < data.length; i++{
    dataset.addValue(data[i], 
null, labels[i]);
  }

  
  JFreeChart chart 
= ChartFactory.createBarChart3D("Weekly Server Load""Work Week 25""MBytes", dataset, PlotOrientation.VERTICAL, falsefalsefalse);
  chart.setBackgroundPaint(
new Color(0xE1E1E1));
  
  CategoryPlot plot 
= chart.getCategoryPlot();
  
  
// 设置Y轴显示整数
  NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
  rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
  
  CategoryAxis domainAxis 
= plot.getDomainAxis();
  
//设置距离图片左端距离
  domainAxis.setLowerMargin(0.05);
  
  BarRenderer3D renderer 
= new BarRenderer3D();
  
//设置柱的颜色
  renderer.setSeriesPaint(0new Color(0xff00));
  plot.setRenderer(renderer);
  
  String filename 
= ServletUtilities.saveChartAsPNG(chart, 300280null, session);
  String graphURL 
= request.getContextPath() + "/displayChart?filename=" + filename;
%>
<html>
<body topmargin="5" leftmargin="5" rightmargin="0">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    3D Bar Chart
</div>
<br>
<img src="<%= graphURL %>" border=0>
</body>
</html>


      画出来的图:

displayChart.JPG

      和ChartDirector画出来的图做一个比较:

threedbar.JPG

posted @ 2005-06-14 18:40 小米 阅读(10683) | 评论 (7)编辑 收藏
      以前一直是用JFreeChart画统计图的,不过JFreeChart画出来的图形不够精细,看起来有些模糊,今天在网上看到另外一个工具ChartDirector,这是一个商业版本的工具,不过也可以免费使用,只是在画出来的图形下面都有一条它的广告条。
      下面是它的一个柱状图的例子:

threedbar.JPG
      范例程序:

<%@page import="ChartDirector.*" %>
<%
//The data for the bar chart
double[] data = {85156179.5211123};

//The labels for the bar chart
String[] labels = {"Mon""Tue""Wed""Thu""Fri"};

//Create a XYChart object of size 300 x 280 pixels
XYChart c = new XYChart(300280);

//Set the plotarea at (45, 30) and of size 200 x 200 pixels
c.setPlotArea(4530200200);

//Add a title to the chart
c.addTitle("Weekly Server Load");

//Add a title to the y axis
c.yAxis().setTitle("MBytes");

//Add a title to the x axis
c.xAxis().setTitle("Work Week 25");

//Add a bar chart layer with green (0x00ff00) bars using the given data
c.addBarLayer(data, 0xff00).set3D();

//Set the labels on the x axis.
c.xAxis().setLabels(labels);

//output the chart
String chart1URL = c.makeSession(request, "chart1");

//include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("""""title='{xLabel}: {value} MBytes'")
    ;
%>
<html>
<body topmargin="5" leftmargin="5" rightmargin="0">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    3D Bar Chart
</div>
<hr color="#000080">
<a href="viewsource.jsp?file=<%=request.getServletPath()%>">
    
<font size="2" face="Verdana">View Chart Source Code</font>
</a>
</div>
<br>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap
="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>


      如果要在柱的顶部显示数值,可以调用Layer的setDataLabelFormat方法设置,范例:layer.setDataLabelFormat("{value}");

      其它的例子可以参考它的文档的说明。ChartDirector的网址:http://www.advsofteng.com

posted @ 2005-06-14 17:46 小米 阅读(5235) | 评论 (5)编辑 收藏
      如果要在程序中定时执行任务,可以使用java.util.Timer这个类实现。使用Timer类需要一个继承了java.util.TimerTask的类。TimerTask是一个虚类,需要实现它的run方法,实际上是他implements了Runnable接口,而把run方法留给子类实现。
      下面是我的一个例子:

class Worker extends TimerTask {
  
public void run() {
    System.
out.println("我在工作啦!");
  }

}

      Timer类用schedule方法或者scheduleAtFixedRate方法启动定时执行,schedule重载了四个版本,scheduleAtFixedRate重载了两个。每个方法的实现都不同,下面是每个方法的说明:

schedule

public void schedule(TimerTask task,
                     long delay)
Schedules the specified task for execution after the specified delay.

Parameters:
task - task to be scheduled.
delay - delay in milliseconds before task is to be executed.
Throws:
IllegalArgumentException - if delay is negative, or delay + System.currentTimeMillis() is negative.
IllegalStateException - if task was already scheduled or cancelled, or timer was cancelled.
说明:该方法会在设定的延时后执行一次任务。

schedule

public void schedule(TimerTask task,
                     Date time)
Schedules the specified task for execution at the specified time. If the time is in the past, the task is scheduled for immediate execution.

Parameters:
task - task to be scheduled.
time - time at which task is to be executed.
Throws:
IllegalArgumentException - if time.getTime() is negative.
IllegalStateException - if task was already scheduled or cancelled, timer was cancelled, or timer thread terminated.
说明:该方法会在指定的时间点执行一次任务。

schedule

public void schedule(TimerTask task,
                     long delay,
                     long period)
Schedules the specified task for repeated fixed-delay execution, beginning after the specified delay. Subsequent executions take place at approximately regular intervals separated by the specified period.

In fixed-delay execution, each execution is scheduled relative to the actual execution time of the previous execution. If an execution is delayed for any reason (such as garbage collection or other background activity), subsequent executions will be delayed as well. In the long run, the frequency of execution will generally be slightly lower than the reciprocal of the specified period (assuming the system clock underlying Object.wait(long) is accurate).

Fixed-delay execution is appropriate for recurring activities that require "smoothness." In other words, it is appropriate for activities where it is more important to keep the frequency accurate in the short run than in the long run. This includes most animation tasks, such as blinking a cursor at regular intervals. It also includes tasks wherein regular activity is performed in response to human input, such as automatically repeating a character as long as a key is held down.

Parameters:
task - task to be scheduled.
delay - delay in milliseconds before task is to be executed.
period - time in milliseconds between successive task executions.
Throws:
IllegalArgumentException - if delay is negative, or delay + System.currentTimeMillis() is negative.
IllegalStateException - if task was already scheduled or cancelled, timer was cancelled, or timer thread terminated.
说明:该方法会在指定的延时后执行任务,并且在设定的周期定时执行任务。

schedule

public void schedule(TimerTask task,
                     Date firstTime,
                     long period)
Schedules the specified task for repeated fixed-delay execution, beginning at the specified time. Subsequent executions take place at approximately regular intervals, separated by the specified period.

In fixed-delay execution, each execution is scheduled relative to the actual execution time of the previous execution. If an execution is delayed for any reason (such as garbage collection or other background activity), subsequent executions will be delayed as well. In the long run, the frequency of execution will generally be slightly lower than the reciprocal of the specified period (assuming the system clock underlying Object.wait(long) is accurate).

Fixed-delay execution is appropriate for recurring activities that require "smoothness." In other words, it is appropriate for activities where it is more important to keep the frequency accurate in the short run than in the long run. This includes most animation tasks, such as blinking a cursor at regular intervals. It also includes tasks wherein regular activity is performed in response to human input, such as automatically repeating a character as long as a key is held down.

Parameters:
task - task to be scheduled.
firstTime - First time at which task is to be executed.
period - time in milliseconds between successive task executions.
Throws:
IllegalArgumentException - if time.getTime() is negative.
IllegalStateException - if task was already scheduled or cancelled, timer was cancelled, or timer thread terminated.
说明:该方法会在指定的时间点执行任务,然后从该时间点开始,在设定的周期定时执行任务。特别的,如果设定的时间点在当前时间之前,任务会被马上执行,然后开始按照设定的周期定时执行任务。

scheduleAtFixedRate

public void scheduleAtFixedRate(TimerTask task,
                                long delay,
                                long period)
Schedules the specified task for repeated fixed-rate execution, beginning after the specified delay. Subsequent executions take place at approximately regular intervals, separated by the specified period.

In fixed-rate execution, each execution is scheduled relative to the scheduled execution time of the initial execution. If an execution is delayed for any reason (such as garbage collection or other background activity), two or more executions will occur in rapid succession to "catch up." In the long run, the frequency of execution will be exactly the reciprocal of the specified period (assuming the system clock underlying Object.wait(long) is accurate).

Fixed-rate execution is appropriate for recurring activities that are sensitive to absolute time, such as ringing a chime every hour on the hour, or running scheduled maintenance every day at a particular time. It is also appropriate for recurring activities where the total time to perform a fixed number of executions is important, such as a countdown timer that ticks once every second for ten seconds. Finally, fixed-rate execution is appropriate for scheduling multiple repeating timer tasks that must remain synchronized with respect to one another.

Parameters:
task - task to be scheduled.
delay - delay in milliseconds before task is to be executed.
period - time in milliseconds between successive task executions.
Throws:
IllegalArgumentException - if delay is negative, or delay + System.currentTimeMillis() is negative.
IllegalStateException - if task was already scheduled or cancelled, timer was cancelled, or timer thread terminated.
说明:该方法和schedule的相同参数的版本类似,不同的是,如果该任务因为某些原因(例如垃圾收集)而延迟执行,那么接下来的任务会尽可能的快速执行,以赶上特定的时间点。

scheduleAtFixedRate

public void scheduleAtFixedRate(TimerTask task,
                                Date firstTime,
                                long period)
Schedules the specified task for repeated fixed-rate execution, beginning at the specified time. Subsequent executions take place at approximately regular intervals, separated by the specified period.

In fixed-rate execution, each execution is scheduled relative to the scheduled execution time of the initial execution. If an execution is delayed for any reason (such as garbage collection or other background activity), two or more executions will occur in rapid succession to "catch up." In the long run, the frequency of execution will be exactly the reciprocal of the specified period (assuming the system clock underlying Object.wait(long) is accurate).

Fixed-rate execution is appropriate for recurring activities that are sensitive to absolute time, such as ringing a chime every hour on the hour, or running scheduled maintenance every day at a particular time. It is also appropriate for recurring activities where the total time to perform a fixed number of executions is important, such as a countdown timer that ticks once every second for ten seconds. Finally, fixed-rate execution is appropriate for scheduling multiple repeating timer tasks that must remain synchronized with respect to one another.

Parameters:
task - task to be scheduled.
firstTime - First time at which task is to be executed.
period - time in milliseconds between successive task executions.
Throws:
IllegalArgumentException - if time.getTime() is negative.
IllegalStateException - if task was already scheduled or cancelled, timer was cancelled, or timer thread terminated.
说明:和上一个方法类似。

      下面是我的一个测试片断:

  public static void main(String[] args) throws Exception {
    Timer timer 
= new Timer(false);
    timer.schedule(
new Worker(), new Date(System.currentTimeMillis() + 1000));
  }
posted @ 2005-06-09 10:29 小米 阅读(33717) | 评论 (7)编辑 收藏

      今天得知,现在住的房子,公司要准备拍卖了,那就是说,我又要搬家了。 这将是我大学毕业后的第四次搬家了,每年搬一次家,有时候真的厌倦了这样的生活,刚适应一个环境,又要重新去适应新的环境。好想拥有自己的房子,但是现在深圳的房价却让人望楼兴叹! 什么时候才能够让老百姓过上安居乐业的生活。
      《我想有个家》,潘美辰的这首老歌,现在最能够代表我的心情了。

posted @ 2005-06-06 21:49 小米 阅读(537) | 评论 (4)编辑 收藏
      Criteria Query是很好的一种面向对象的查询实现,它提供了一种示例查询的方式。该方式根据已有的对象,查找数据库中属性匹配的其他对象。
      下面是一个场景片断,模糊查找数据库中用户帐号为'test',邮件地址为'georgehill@21cn.com'的实例,忽略大小写。

  public void testCriteriaExampleQuery() throws Exception {
    User user 
= new User();
    user.setAccount(
"test");
    user.setEmail(
"georgehill@21cn.com");
    
    Criteria criteria 
= session.createCriteria(User.class).add(Example.create(user).enableLike(MatchMode.ANYWHERE).ignoreCase());
    List list 
= criteria.list();
    
    
if (list != null{
      
for (int i = 0; i < list.size(); i++{
        System.
out.println(((User) list.get(i)).getAccount());
      }

    }

  }

      示例查询需要生成Example实例,可以通过Example的静态方法create生成。Example类有下面的几个方法指定查询的方式:

excludeZeroes

public Example excludeZeroes()
Exclude zero-valued properties


excludeNone

public Example excludeNone()
Don't exclude null or zero-valued properties


enableLike

public Example enableLike(MatchMode matchMode)
Use the "like" operator for all string-valued properties


enableLike

public Example enableLike()
Use the "like" operator for all string-valued properties


ignoreCase

public Example ignoreCase()
Ignore case for all string-valued properties


excludeProperty

public Example excludeProperty(String name)
Exclude a particular named property



      当用enableLike()方法时,可以通过MatchMode指定匹配的方式。MatchMode提供了四种匹配的方式:

Field Summary
static MatchMode ANYWHERE
          Match the pattern anywhere in the string
static MatchMode END
          Match the end of the string to the pattern
static MatchMode EXACT
          Match the entire string to the pattern
static MatchMode START
          Match the start of the string to the pattern
posted @ 2005-06-03 17:27 小米 阅读(2175) | 评论 (3)编辑 收藏
     摘要:       利用JavaMail的API可以快速的实现发送邮件的功能。下面是我使用的一个简单的实例,实现了简单的文本邮件的发送。 import java.io.*;import java.util.*;import javax.activation.*;import javax.mail.*;...  阅读全文
posted @ 2005-06-02 16:30 小米 阅读(2204) | 评论 (7)编辑 收藏
      好怀念以前可以过六一儿童节的时候,可以放假,学校还会组织活动,每到这天,都可以名正言顺的出去玩。呵呵。现在可没有六一儿童节过了。
posted @ 2005-06-01 16:29 小米 阅读(430) | 评论 (0)编辑 收藏
      上个月过了理论考试,昨天终于第一次开起了汽车。呵呵,一开始好紧张啊,给师傅狂骂。有两次还差点撞到墙。后来熟悉了后,就好了很多了。呵呵,第一天学会了怎么启动,停车,打档和转方向盘。上手还是很快滴!不过,想起要上路,我就感觉恐怖。
posted @ 2005-05-26 10:21 小米 阅读(475) | 评论 (0)编辑 收藏
      以前在写程序的时候,碰到需要比较两个有可能为null的实例时,为了避免出现NullPointerException,经常用这样的一段代码来比较:

    Object obj1 = "abc";
    Object obj2 
= "cde";
    
    
if ((obj1 == null && obj2 == null|| (obj1 != null && obj1.equals(obj2)) 
        
|| (obj2 != null && obj2.equals(obj1))) {
      System.
out.println("equals");
    }

      这样的程序,读起来真是挺拗口。我一直没有想到什么好的方法解决这个问题,直到今天在看到JDK的AbstractList源码的equals方法的实现时,看到这一段:

        if (!(o1==null ? o2==null : o1.equals(o2)))
        
return false;

      原来用三元运算符可以很好的解决这个问题,呵呵,我前面的程序可以改写成:

    Object obj1 = "abc";
    Object obj2 
= "cde";
    
    
if (obj1 == null ? obj2 == null : obj1.equals(obj2))
      System.
out.println("equals");

      真是简洁多了!
posted @ 2005-05-25 17:00 小米 阅读(1333) | 评论 (0)编辑 收藏
      从对象池中获取的实例,因为并不清楚该channel是否已经设置成正确的状态,所以在使用时最好重新设置一遍。有以下几点需要注意:
      1.在使用阻塞IO时,需要把该channel设置成阻塞的,即需要调用SocketChannel.configureBlocking(true);
      2.在使用非阻塞IO时,需要把该channel设置成非阻塞的,即需要调用SocketChannel.configureBlocking(false);
      3.如果该channel注册了selector,那么在返回该实例到对象池中,需要把注册的selector清除,即需要调用Selector的close方法。

      下面是一段应用场景的例子:


        
// 把命令输出
        channel.configureBlocking(true);
        PrintWriter writer 
= new PrintWriter(channel.socket().getOutputStream(), false);
        writer.write(command.endsWith(
"\n"? command : command + "\n");
        writer.flush();

        channel.configureBlocking(
false);

        
// 创建Selector
        Selector selector = Selector.open();
        
// 向Selector注册我们需要的READ事件
        SelectionKey skey = channel.register(selector, SelectionKey.OP_READ);

        boolean stop 
= false;
        
int n = 0;
        
int read = 0;
        ByteBuffer buffer 
= ByteBuffer.allocate(1024);

        
// 轮询
        while (!stop) {
          
// 获取Selector返回的时间值
          n = selector.select();

          
// 当传回的值大于0事,读事件发生了
          if (n > 0{
         
// 处理发生的事件
         
          }

        }


        selector.close();
posted @ 2005-05-25 15:02 小米 阅读(3192) | 评论 (0)编辑 收藏
仅列出标题
共6页: 上一页 1 2 3 4 5 6 下一页