這個(gè)范例說明如何用JFreeChart畫簡單的柱狀圖,下面是一個(gè)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();
// 設(shè)置Y軸顯示整數(shù)
NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
CategoryAxis domainAxis = plot.getDomainAxis();
//設(shè)置距離圖片左端距離
domainAxis.setLowerMargin(0.05);
BarRenderer3D renderer = new BarRenderer3D();
//設(shè)置柱的顏色
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畫出來的圖做一個(gè)比較:

以前一直是用JFreeChart畫統(tǒng)計(jì)圖的,不過JFreeChart畫出來的圖形不夠精細(xì),看起來有些模糊,今天在網(wǎng)上看到另外一個(gè)工具ChartDirector,這是一個(gè)商業(yè)版本的工具,不過也可以免費(fèi)使用,只是在畫出來的圖形下面都有一條它的廣告條。
下面是它的一個(gè)柱狀圖的例子:

范例程序:
<%@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>

如果要在柱的頂部顯示數(shù)值,可以調(diào)用Layer的setDataLabelFormat方法設(shè)置,范例:layer.setDataLabelFormat("{value}");
其它的例子可以參考它的文檔的說明。ChartDirector的網(wǎng)址:http://www.advsofteng.com
如果要在程序中定時(shí)執(zhí)行任務(wù),可以使用java.util.Timer這個(gè)類實(shí)現(xiàn)。使用Timer類需要一個(gè)繼承了java.util.TimerTask的類。TimerTask是一個(gè)虛類,需要實(shí)現(xiàn)它的run方法,實(shí)際上是他implements了Runnable接口,而把run方法留給子類實(shí)現(xiàn)。
下面是我的一個(gè)例子:

class Worker extends TimerTask
{

public void run()
{
System.out.println("我在工作啦!");
}
} Timer類用schedule方法或者scheduleAtFixedRate方法啟動(dòng)定時(shí)執(zhí)行,schedule重載了四個(gè)版本,scheduleAtFixedRate重載了兩個(gè)。每個(gè)方法的實(shí)現(xiàn)都不同,下面是每個(gè)方法的說明:
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.
說明:該方法會(huì)在設(shè)定的延時(shí)后執(zhí)行一次任務(wù)。
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.
說明:該方法會(huì)在指定的時(shí)間點(diǎn)執(zhí)行一次任務(wù)。
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.
說明:該方法會(huì)在指定的延時(shí)后執(zhí)行任務(wù),并且在設(shè)定的周期定時(shí)執(zhí)行任務(wù)。
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.
說明:該方法會(huì)在指定的時(shí)間點(diǎn)執(zhí)行任務(wù),然后從該時(shí)間點(diǎn)開始,在設(shè)定的周期定時(shí)執(zhí)行任務(wù)。特別的,如果設(shè)定的時(shí)間點(diǎn)在當(dāng)前時(shí)間之前,任務(wù)會(huì)被馬上執(zhí)行,然后開始按照設(shè)定的周期定時(shí)執(zhí)行任務(wù)。
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的相同參數(shù)的版本類似,不同的是,如果該任務(wù)因?yàn)槟承┰颍ɡ缋占┒舆t執(zhí)行,那么接下來的任務(wù)會(huì)盡可能的快速執(zhí)行,以趕上特定的時(shí)間點(diǎn)。
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.
說明:和上一個(gè)方法類似。
下面是我的一個(gè)測試片斷:

public static void main(String[] args) throws Exception
{
Timer timer = new Timer(false);
timer.schedule(new Worker(), new Date(System.currentTimeMillis() + 1000));
}
今天得知,現(xiàn)在住的房子,公司要準(zhǔn)備拍賣了,那就是說,我又要搬家了。
這將是我大學(xué)畢業(yè)后的第四次搬家了,每年搬一次家,有時(shí)候真的厭倦了這樣的生活,剛適應(yīng)一個(gè)環(huán)境,又要重新去適應(yīng)新的環(huán)境。好想擁有自己的房子,但是現(xiàn)在深圳的房價(jià)卻讓人望樓興嘆!
什么時(shí)候才能夠讓老百姓過上安居樂業(yè)的生活。
《我想有個(gè)家》,潘美辰的這首老歌,現(xiàn)在最能夠代表我的心情了。
Criteria Query是很好的一種面向?qū)ο蟮牟樵儗?shí)現(xiàn),它提供了一種示例查詢的方式。該方式根據(jù)已有的對(duì)象,查找數(shù)據(jù)庫中屬性匹配的其他對(duì)象。
下面是一個(gè)場景片斷,模糊查找數(shù)據(jù)庫中用戶帳號(hào)為'test',郵件地址為
'georgehill@21cn.com'的實(shí)例,忽略大小寫。

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實(shí)例,可以通過Example的靜態(tài)方法create生成。Example類有下面的幾個(gè)方法指定查詢的方式:
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
-
當(dāng)用enableLike()方法時(shí),可以通過MatchMode指定匹配的方式。MatchMode提供了四種匹配的方式:
摘要: 利用JavaMail的API可以快速的實(shí)現(xiàn)發(fā)送郵件的功能。下面是我使用的一個(gè)簡單的實(shí)例,實(shí)現(xiàn)了簡單的文本郵件的發(fā)送。
import java.io.*;import java.util.*;import javax.activation.*;import javax.mail.*;...
閱讀全文
好懷念以前可以過六一兒童節(jié)的時(shí)候,可以放假,學(xué)校還會(huì)組織活動(dòng),每到這天,都可以名正言順的出去玩。呵呵。現(xiàn)在可沒有六一兒童節(jié)過了。
上個(gè)月過了理論考試,昨天終于第一次開起了汽車。呵呵,一開始好緊張啊,給師傅狂罵。

有兩次還差點(diǎn)撞到墻。

后來熟悉了后,就好了很多了。呵呵,第一天學(xué)會(huì)了怎么啟動(dòng),停車,打檔和轉(zhuǎn)方向盤。上手還是很快滴!

不過,想起要上路,我就感覺恐怖。
以前在寫程序的時(shí)候,碰到需要比較兩個(gè)有可能為null的實(shí)例時(shí),為了避免出現(xiàn)NullPointerException,經(jīng)常用這樣的一段代碼來比較:
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");
} 這樣的程序,讀起來真是挺拗口。我一直沒有想到什么好的方法解決這個(gè)問題,直到今天在看到JDK的AbstractList源碼的equals方法的實(shí)現(xiàn)時(shí),看到這一段:
if (!(o1==null ? o2==null : o1.equals(o2)))
return false; 原來用三元運(yùn)算符可以很好的解決這個(gè)問題,呵呵,我前面的程序可以改寫成:
Object obj1 = "abc";
Object obj2 = "cde";
if (obj1 == null ? obj2 == null : obj1.equals(obj2))
System.out.println("equals"); 真是簡潔多了!
從對(duì)象池中獲取的實(shí)例,因?yàn)椴⒉磺宄揷hannel是否已經(jīng)設(shè)置成正確的狀態(tài),所以在使用時(shí)最好重新設(shè)置一遍。有以下幾點(diǎn)需要注意:
1.在使用阻塞IO時(shí),需要把該channel設(shè)置成阻塞的,即需要調(diào)用SocketChannel.configureBlocking(true);
2.在使用非阻塞IO時(shí),需要把該channel設(shè)置成非阻塞的,即需要調(diào)用SocketChannel.configureBlocking(false);
3.如果該channel注冊(cè)了selector,那么在返回該實(shí)例到對(duì)象池中,需要把注冊(cè)的selector清除,即需要調(diào)用Selector的close方法。
下面是一段應(yīng)用場景的例子:


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

channel.configureBlocking(false);

// 創(chuàng)建Selector
Selector selector = Selector.open();
// 向Selector注冊(cè)我們需要的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返回的時(shí)間值
n = selector.select();

// 當(dāng)傳回的值大于0事,讀事件發(fā)生了

if (n > 0)
{
// 處理發(fā)生的事件

}
}

selector.close();