這個范例說明如何用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 =
{85, 156, 179.5, 211, 123};
//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, false, false, false);
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(0, new Color(0xff00));
plot.setRenderer(renderer);
String filename = ServletUtilities.saveChartAsPNG(chart, 300, 280, null, 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>

畫出來的圖:

和ChartDirector畫出來的圖做一個比較:

posted @
2005-06-14 18:40 小米 閱讀(10699) |
評論 (7) |
編輯 收藏
以前一直是用JFreeChart畫統計圖的,不過JFreeChart畫出來的圖形不夠精細,看起來有些模糊,今天在網上看到另外一個工具ChartDirector,這是一個商業版本的工具,不過也可以免費使用,只是在畫出來的圖形下面都有一條它的廣告條。
下面是它的一個柱狀圖的例子:

范例程序:
<%@page import="ChartDirector.*" %>
<%
//The data for the bar chart

double[] data =
{85, 156, 179.5, 211, 123};

//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(300, 280);

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

//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 小米 閱讀(5249) |
評論 (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 小米 閱讀(33751) |
評論 (7) |
編輯 收藏
今天得知,現在住的房子,公司要準備拍賣了,那就是說,我又要搬家了。
這將是我大學畢業后的第四次搬家了,每年搬一次家,有時候真的厭倦了這樣的生活,剛適應一個環境,又要重新去適應新的環境。好想擁有自己的房子,但是現在深圳的房價卻讓人望樓興嘆!
什么時候才能夠讓老百姓過上安居樂業的生活。
《我想有個家》,潘美辰的這首老歌,現在最能夠代表我的心情了。
posted @
2005-06-06 21:49 小米 閱讀(553) |
評論 (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提供了四種匹配的方式:
posted @
2005-06-03 17:27 小米 閱讀(2191) |
評論 (3) |
編輯 收藏
摘要: 利用JavaMail的API可以快速的實現發送郵件的功能。下面是我使用的一個簡單的實例,實現了簡單的文本郵件的發送。
import java.io.*;import java.util.*;import javax.activation.*;import javax.mail.*;...
閱讀全文
posted @
2005-06-02 16:30 小米 閱讀(2221) |
評論 (7) |
編輯 收藏
好懷念以前可以過六一兒童節的時候,可以放假,學校還會組織活動,每到這天,都可以名正言順的出去玩。呵呵。現在可沒有六一兒童節過了。
posted @
2005-06-01 16:29 小米 閱讀(443) |
評論 (0) |
編輯 收藏
上個月過了理論考試,昨天終于第一次開起了汽車。呵呵,一開始好緊張啊,給師傅狂罵。

有兩次還差點撞到墻。

后來熟悉了后,就好了很多了。呵呵,第一天學會了怎么啟動,停車,打檔和轉方向盤。上手還是很快滴!

不過,想起要上路,我就感覺恐怖。
posted @
2005-05-26 10:21 小米 閱讀(486) |
評論 (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 小米 閱讀(1348) |
評論 (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 小米 閱讀(3207) |
評論 (0) |
編輯 收藏