<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>权记 &#187; java</title>
	<atom:link href="http://www.quanlei.com/tag/java/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.quanlei.com</link>
	<description>一个关于我们生活点滴的网站，一个记录我们酸甜苦辣的日志。</description>
	<lastBuildDate>Sun, 06 Jun 2010 01:10:16 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>利用JSON插件进行数据交换格式(includeProperties和excludeProperties用法)</title>
		<link>http://www.quanlei.com/2010/06/struts2-json/</link>
		<comments>http://www.quanlei.com/2010/06/struts2-json/#comments</comments>
		<pubDate>Sat, 05 Jun 2010 15:58:22 +0000</pubDate>
		<dc:creator>小权</dc:creator>
				<category><![CDATA[技术]]></category>
		<category><![CDATA[编程相关]]></category>
		<category><![CDATA[excludeProperties]]></category>
		<category><![CDATA[includeProperties]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[json]]></category>
		<category><![CDATA[struts]]></category>
		<category><![CDATA[web]]></category>

		<guid isPermaLink="false">http://www.quanlei.com/2010/06/%e5%88%a9%e7%94%a8json%e6%8f%92%e4%bb%b6%e8%bf%9b%e8%a1%8c%e6%95%b0%e6%8d%ae%e4%ba%a4%e6%8d%a2%e6%a0%bc%e5%bc%8f/</guid>
		<description><![CDATA[JSON（Java Script Object Notation），是一种语言无关的数据交换格式。 JSON插件是Structs 2 的Ajax插件，通过利用JSON插件，开发者可以很方便，灵活的利用Ajax进行开发。 Json是一种轻量级的数据交换格式，JSon插件提供了一种名为json的Action ResultType 。一旦为Action指定了该结果处理类型，JSON插件就会自动将Action里的数据序列化成JSON格式的数据，并返回给客户端物理视图的JavaScript。简单的说，JSON插件允许我们在JavaScript中异步的调用Action。 而且Action不需要指定视图来显示Action的信息显示而是由JSON插件来负责具体将Action里面具体的信息返回给调用页面。Json的数据格式可简单如下形式： person = { name: &#8216;Jim&#8217;,age: 18,gender: &#8216;man&#8217;}。 如果action的属性很多，我们想要从Action返回到调用页面的数据。这个时候配置includeProperties或者 excludeProperties拦截器即可。而这2个拦截器的定义都在struts2的json-default包内，所以要使用该拦截器的包都要继承自json-default。 &#60;struts&#62; &#60;constant value=&#34;spring&#34; name=&#34;struts.objectFactory&#34; /&#62; &#60;include file=&#34;struts-admin.xml&#34;&#62;&#60;/include&#62; &#60;package name=&#34;default&#34; extends=&#34;json-default&#34;&#62; &#60;action class=&#34;com.person.PersonAction&#34; name=&#34;person&#34; method=&#34;view&#34;&#62; &#60;result type=&#34;json&#34;&#62; &#60;param name=&#34;includeProperties&#34;&#62;person\.name,persoon\.age,person\.gender &#60;/param&#62; &#60;/result&#62; &#60;/action&#62; &#60;/package&#62; &#60;/struts&#62; 经过测试，下面的设置也是可以的，就是在includeProperties里面直接写你所在Action的属性 &#60;struts&#62; &#60;constant value=&#34;spring&#34; name=&#34;struts.objectFactory&#34; /&#62; &#60;include file=&#34;struts-admin.xml&#34;&#62;&#60;/include&#62; &#60;package name=&#34;default&#34; extends=&#34;json-default&#34;&#62; &#60;action [...]]]></description>
			<content:encoded><![CDATA[<p>JSON（Java Script Object Notation），是一种语言无关的数据交换格式。 JSON插件是Structs 2 的Ajax插件，通过利用JSON插件，开发者可以很方便，灵活的利用Ajax进行开发。</p>
<p>Json是一种轻量级的数据交换格式，JSon插件提供了一种名为json的Action ResultType 。一旦为Action指定了该结果处理类型，JSON插件就会自动将Action里的数据序列化成JSON格式的数据，并返回给客户端物理视图的JavaScript。简单的说，JSON插件允许我们在JavaScript中异步的调用Action。</p>
<p>而且Action不需要指定视图来显示Action的信息显示而是由JSON插件来负责具体将Action里面具体的信息返回给调用页面。Json的数据格式可简单如下形式： person = { name: &#8216;Jim&#8217;,age: 18,gender: &#8216;man&#8217;}。</p>
<p>如果action的属性很多，我们想要从Action返回到调用页面的数据。这个时候配置includeProperties或者 excludeProperties拦截器即可。而这2个拦截器的定义都在struts2的json-default包内，所以要使用该拦截器的包都要继承自json-default。</p>
<pre class="brush: xml;">
&lt;struts&gt;
    &lt;constant value=&quot;spring&quot; name=&quot;struts.objectFactory&quot; /&gt;
    &lt;include file=&quot;struts-admin.xml&quot;&gt;&lt;/include&gt;
    &lt;package name=&quot;default&quot; extends=&quot;json-default&quot;&gt;
        &lt;action class=&quot;com.person.PersonAction&quot; name=&quot;person&quot; method=&quot;view&quot;&gt;
            &lt;result type=&quot;json&quot;&gt;
                &lt;param name=&quot;includeProperties&quot;&gt;person\.name,persoon\.age,person\.gender &lt;/param&gt;
            &lt;/result&gt;
        &lt;/action&gt;
    &lt;/package&gt;
&lt;/struts&gt;
</pre>
<p><span id="more-1626"></span><br />
<span style="color: #800000;">经过测试，下面的设置也是可以的，就是在includeProperties里面直接写你所在Action的属性</span></p>
<pre class="brush: xml;">
&lt;struts&gt;
    &lt;constant value=&quot;spring&quot; name=&quot;struts.objectFactory&quot; /&gt;
    &lt;include file=&quot;struts-admin.xml&quot;&gt;&lt;/include&gt;
    &lt;package name=&quot;default&quot; extends=&quot;json-default&quot;&gt;
        &lt;action class=&quot;com.person.PersonAction&quot; name=&quot;person&quot; method=&quot;view&quot;&gt;
            &lt;result type=&quot;json&quot;&gt;
                &lt;param name=&quot;includeProperties&quot;&gt;name,age,gender &lt;/param&gt;
            &lt;/result&gt;
        &lt;/action&gt;
    &lt;/package&gt;
&lt;/struts&gt;
</pre>
<p>利用Struts 2的支持的可配置结果，可以达到过滤器的效果。Action的处理结果配置支持正则表达式。但是如果返回的对象是一个数组格式的Json数据。比如 peson Bean中有对象persion1&#8230;person9，而我只要JSON插件，则可以用如下的正则表达式。</p>
<pre class="brush: xml;">
&lt;struts&gt;
    &lt;constant value=&quot;spring&quot; name=&quot;struts.objectFactory&quot; /&gt;
    &lt;include file=&quot;struts-admin.xml&quot;&gt;&lt;/include&gt;
    &lt;package name=&quot;default&quot; extends=&quot;json-default&quot;&gt;
        &lt;action class=&quot;com.person.PersonAction&quot; name=&quot;person&quot; method=&quot;view&quot;&gt;
            &lt;result type=&quot;json&quot;&gt;
                &lt;param name=&quot;includeProperties&quot;&gt;person\.name,persoon\.age,person\.gender &lt;/param&gt;
            &lt;/result&gt;
        &lt;/action&gt;
    &lt;/package&gt;
&lt;/struts&gt;
&lt;!--利用Struts 2的支持的可配置结果，可以达到过滤器的效果。Action的处理结果配置支持正则表达式。 但是如果返回的对象是一个数组格式的Json数据。比如peson Bean中有对象persion1...person9，而我只要person1的json数据， 则可以用如下的正则表达式。 --&gt;
&lt;struts&gt;
    &lt;constant value=&quot;spring&quot; name=&quot;struts.objectFactory&quot; /&gt;
    &lt;include file=&quot;struts-admin.xml&quot;&gt;&lt;/include&gt;
    &lt;package name=&quot;default&quot; extends=&quot;json-default&quot;&gt;
        &lt;action class=&quot;com.person.PersonAction&quot; name=&quot;person&quot; method=&quot;view&quot;&gt;
            &lt;result type=&quot;json&quot;&gt;
                &lt;param name=&quot;includeProperties&quot;&gt;person\[\d+\]\.person1 &lt;/param&gt;
            &lt;/result&gt;
        &lt;/action&gt;
    &lt;/package&gt;
&lt;/struts&gt;
&lt;!--excludeProperties拦截器的用法与此类同，如果拦截的仅仅是一个对象，如果拦截掉person Bean的整个对象。 --&gt;
&lt;struts&gt;
    &lt;constant value=&quot;spring&quot; name=&quot;struts.objectFactory&quot; /&gt;
    &lt;include file=&quot;struts-admin.xml&quot;&gt;&lt;/include&gt;
    &lt;package name=&quot;default&quot; extends=&quot;json-default&quot;&gt;
        &lt;action class=&quot;com.person.PersonAction&quot; name=&quot;person&quot; method=&quot;view&quot;&gt;
            &lt;result type=&quot;json&quot;&gt;
                &lt;param name=&quot;excludeProperties&quot;&gt;person &lt;/param&gt;
            &lt;/result&gt;
        &lt;/action&gt;
    &lt;/package&gt;
&lt;/struts&gt;
</pre>
<p>需要注意的是,如果用JSON插件把返回结果定为JSON。而JSON的原理是在ACTION中的get方法都会序列化，所以前面是get的方法只要没指定不序列化，都会执行，那么可以在该方法的前面加注解声明该方法不做序列化。</p>
<pre class="brush: java;">
    @JSON(serialize = false)
    public User getUser() {
        return this.User;
    }

    @JSON(format = &quot;yyyy-MM-dd&quot;)
    public Date getStartDate() {
        return this.startDate;
    }
</pre>
<p>原文出处：http://developer.51cto.com/art/201001/176090.htm</p>
<p>Apache Struts Json 介绍：http://struts.apache.org/2.1.8/docs/json-plugin.html</p>
]]></content:encoded>
			<wfw:commentRss>http://www.quanlei.com/2010/06/struts2-json/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Spring Filter Ordering</title>
		<link>http://www.quanlei.com/2010/05/spring-filter-ordering/</link>
		<comments>http://www.quanlei.com/2010/05/spring-filter-ordering/#comments</comments>
		<pubDate>Wed, 26 May 2010 11:29:27 +0000</pubDate>
		<dc:creator>小权</dc:creator>
				<category><![CDATA[技术]]></category>
		<category><![CDATA[编程相关]]></category>
		<category><![CDATA[Filter]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[Spring]]></category>

		<guid isPermaLink="false">http://www.quanlei.com/?p=1592</guid>
		<description><![CDATA[相关介绍： Spring 官方英文：http://static.springsource.org/spring-security/site/docs/3.1.x/reference/security-filter-chain.html#d4e1307 中文翻译：http://www.family168.com/tutorial/springsecurity3/html/web-infrastructure.html#d0e2828 更多介绍：http://www.family168.com/oa/springsecurity/html/ch101-filters.html]]></description>
			<content:encoded><![CDATA[<p style="text-align: center;"><a href="http://www.quanlei.com/wp-content/uploads/2010/05/Spring_Filter_Order.png"><img class="size-full wp-image-1593  aligncenter" title="Spring_Filter_Order" src="http://www.quanlei.com/wp-content/uploads/2010/05/Spring_Filter_Order.png" alt="" width="428" height="738" /></a></p>
<p>相关介绍：</p>
<blockquote><p>Spring 官方英文：<a href="http://static.springsource.org/spring-security/site/docs/3.1.x/reference/security-filter-chain.html#d4e1307">http://static.springsource.org/spring-security/site/docs/3.1.x/reference/security-filter-chain.html#d4e1307</a></p>
<p>中文翻译：<a href="http://www.family168.com/tutorial/springsecurity3/html/web-infrastructure.html#d0e2828">http://www.family168.com/tutorial/springsecurity3/html/web-infrastructure.html#d0e2828</a></p>
<p>更多介绍：<a href="http://www.family168.com/oa/springsecurity/html/ch101-filters.html">http://www.family168.com/oa/springsecurity/html/ch101-filters.html</a>
</p></blockquote>
]]></content:encoded>
			<wfw:commentRss>http://www.quanlei.com/2010/05/spring-filter-ordering/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Drawing in code</title>
		<link>http://www.quanlei.com/2010/02/drawing-in-code/</link>
		<comments>http://www.quanlei.com/2010/02/drawing-in-code/#comments</comments>
		<pubDate>Tue, 02 Feb 2010 09:34:44 +0000</pubDate>
		<dc:creator>小权</dc:creator>
				<category><![CDATA[技术]]></category>
		<category><![CDATA[编程相关]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[Swing]]></category>
		<category><![CDATA[UI]]></category>

		<guid isPermaLink="false">http://www.quanlei.com/?p=1248</guid>
		<description><![CDATA[之前介绍了一个Swing做的原子钟的效果 “Swing Nixieclock（原子钟）效果”，作者放出了制作 Swing原子钟 制作的主要元素 &#8211; 原子钟的制造过程。 想看制作过程的移步这里： Part One 先通过绘图工具，绘出原型，绘制过程以及绘制时的参数，要在Swing中使用。 Part Two 将原型绘制过程中的一些数据，以Java Code 的形式在Swing中体现出来，步骤和通过绘图工具绘制时差不多，一步步来。]]></description>
			<content:encoded><![CDATA[<p>之前介绍了一个Swing做的原子钟的效果 “<a href="http://www.quanlei.com/2010/01/swing-nixieclock/">Swing Nixieclock（原子钟）效果</a>”，作者放出了制作 Swing原子钟 制作的主要元素 &#8211; 原子钟的制造过程。<br />
<a href="http://www.quanlei.com/wp-content/uploads/2010/02/Screenshot.png"><img class="aligncenter size-full wp-image-1250" title="NixieClock" src="http://www.quanlei.com/wp-content/uploads/2010/02/Screenshot.png" alt="" width="268" height="272" /></a><br />
想看制作过程的移步这里：</p>
<p><a href="http://www.jug-muenster.de/drawing-in-code-part-1-379/">Part One</a></p>
<blockquote><p>先通过绘图工具，绘出原型，绘制过程以及绘制时的参数，要在Swing中使用。</p></blockquote>
<p><a href="http://www.jug-muenster.de/drawing-in-code-part-2-2-384/">Part Two</a></p>
<blockquote><p>将原型绘制过程中的一些数据，以Java Code 的形式在Swing中体现出来，步骤和通过绘图工具绘制时差不多，一步步来。</p></blockquote>
]]></content:encoded>
			<wfw:commentRss>http://www.quanlei.com/2010/02/drawing-in-code/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Swing Nixieclock（原子钟）效果</title>
		<link>http://www.quanlei.com/2010/01/swing-nixieclock/</link>
		<comments>http://www.quanlei.com/2010/01/swing-nixieclock/#comments</comments>
		<pubDate>Wed, 27 Jan 2010 03:43:43 +0000</pubDate>
		<dc:creator>小权</dc:creator>
				<category><![CDATA[技术]]></category>
		<category><![CDATA[编程相关]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[Swing]]></category>

		<guid isPermaLink="false">http://www.quanlei.com/?p=1221</guid>
		<description><![CDATA[在JavaEye上看的这个，转发一下，原文：http://www.javaeye.com/news/13151 Gerrit 受到了这些设计的启发，尝试着使用Swing创造出了NixieClock（原子钟）效果。 *首先，在Fireworks中创建了一个原型 *第二步是建立一个JavaBean并将其转成Swing，这个步骤要花费很多时间 *第三步是建立一个包含时钟逻辑的JFrame和6个nixie number的组件 结果如下： 下载NixieClock：http://www.jug-muenster.de/wp-content/uploads/2010/01/NixieClock.zip]]></description>
			<content:encoded><![CDATA[<p>在JavaEye上看的这个，转发一下，原文：http://www.javaeye.com/news/13151</p>
<p><a href="http://www.jug-muenster.de/swing-nixieclock-321/">Gerrit </a>受到了<a href="http://www.electricstuff.co.uk/nixiegallery.html">这些设计</a>的启发，尝试着使用Swing创造出了NixieClock（原子钟）效果。</p>
<p>*首先，在Fireworks中创建了一个原型</p>
<p><img src="http://www.jug-muenster.de/wp-content/uploads/2010/01/ishot-2.png" alt="" /></p>
<p>*第二步是建立一个JavaBean并将其转成Swing，这个步骤要花费很多时间</p>
<p>*第三步是建立一个包含时钟逻辑的JFrame和6个nixie number的组件</p>
<p>结果如下：<br />
<img src="http://www.jug-muenster.de/wp-content/uploads/2010/01/ishot-1.png" alt="" /></p>
<p>下载NixieClock：<a href="http://www.jug-muenster.de/wp-content/uploads/2010/01/NixieClock.zip">http://www.jug-muenster.de/wp-content/uploads/2010/01/NixieClock.zip</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.quanlei.com/2010/01/swing-nixieclock/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>[09/51-52周主题] – Java Net and XML parser</title>
		<link>http://www.quanlei.com/2009/12/java-net-and-xml-parser/</link>
		<comments>http://www.quanlei.com/2009/12/java-net-and-xml-parser/#comments</comments>
		<pubDate>Sun, 27 Dec 2009 08:29:09 +0000</pubDate>
		<dc:creator>小权</dc:creator>
				<category><![CDATA[周主题]]></category>
		<category><![CDATA[编程相关]]></category>
		<category><![CDATA[http]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[twitter]]></category>
		<category><![CDATA[xml]]></category>

		<guid isPermaLink="false">http://www.quanlei.com/?p=1061</guid>
		<description><![CDATA[本周主题：Java Net and XML Parser 分两部分：一部Java Net(大部分来自Java Doc), 一部分XML Parser， 通过一个Twitter的例子来描述简单的使用情况。 一、Java Net java.net 包的概述： java.net包大致可分为两部分： 低级API &#8211; 用于处理以下抽象： 地址，也就是网络标识符，如 IP 地址。 套接字，也就是基本双向数据通信机制。 接口，用于描述网络接口。 高级API &#8211; 用于处理以下抽象： URI，表示统一资源标识符。 URL，表示统一资源定位符。 连接，表示到 URL 所指向资源的连接。 地址 在整个 java.net API 中，地址或者用作主机标识符或者用作套接字端点标识符。 InetAddress 类是表示 IP（Internet 协议）地址的抽象，它拥有两个子类： 用于 IPv4 地址的 Inet4Address。 用于 IPv6 地址的 Inet6Address。 但是，在大多数情况下，不必直接处理子类，因为 InetAddress 抽象应该覆盖大多数必需的功能。 套接字 套接字是在网络上建立机器之间的通信链接的方法。java.net 包提供 [...]]]></description>
			<content:encoded><![CDATA[<h2>本周主题：Java Net and XML Parser</h2>
<p>分两部分：一部Java Net(大部分来自Java Doc), 一部分XML Parser， 通过一个Twitter的例子来描述简单的使用情况。</p>
<h3>一、Java Net</h3>
<p>java.net 包的概述：</p>
<p>java.net包大致可分为两部分：</p>
<h4>低级API &#8211; 用于处理以下抽象：</h4>
<ul>
<li><em>地址</em>，也就是网络标识符，如 IP 地址。</li>
<li><em>套接字</em>，也就是基本双向数据通信机制。</li>
<li><em>接口</em>，用于描述网络接口。</li>
</ul>
<h4>高级API &#8211; 用于处理以下抽象：</h4>
<ul>
<li><em>URI</em>，表示统一资源标识符。</li>
<li><em>URL</em>，表示统一资源定位符。</li>
<li><em>连接</em>，表示到 <em>URL</em> 所指向资源的连接。</li>
</ul>
<h4>地址</h4>
<p>在整个 java.net API 中，地址或者用作主机标识符或者用作套接字端点标识符。</p>
<p>InetAddress 类是表示 IP（Internet 协议）地址的抽象，它拥有两个子类：</p>
<ul>
<li>用于 IPv4 地址的 <a title="java.net 中的类" href="http://gceclub.sun.com.cn/Java_Docs/html/zh_CN/api/java/net/Inet4Address.html"><code>Inet4Address</code></a>。</li>
<li>用于 IPv6 地址的 <a title="java.net 中的类" href="http://gceclub.sun.com.cn/Java_Docs/html/zh_CN/api/java/net/Inet6Address.html"><code>Inet6Address</code></a>。</li>
</ul>
<p>但是，在大多数情况下，不必直接处理子类，因为 InetAddress 抽象应该覆盖大多数必需的功能。</p>
<h4>套接字</h4>
<p>套接字是在网络上建立机器之间的通信链接的方法。java.net 包提供 4 种套接字：</p>
<ul>
<li><a title="java.net 中的类" href="http://gceclub.sun.com.cn/Java_Docs/html/zh_CN/api/java/net/Socket.html"><code>Socket</code></a> 是 TCP 客户端 API，通常用于将 (<code>java.net.Socket.connect(SocketAddress)</code>) 连接到远程主机。</li>
<li><a title="java.net 中的类" href="http://gceclub.sun.com.cn/Java_Docs/html/zh_CN/api/java/net/ServerSocket.html"><code>ServerSocket</code></a> 是 TCP 服务器 API，通常接受 (<code>java.net.ServerSocket.accept</code>) 源于客户端套接字的连接。</li>
<li><a title="java.net 中的类" href="http://gceclub.sun.com.cn/Java_Docs/html/zh_CN/api/java/net/DatagramSocket.html"><code>DatagramSocket</code></a> 是 UDP 端点 API，用于发送和接收 <code>java.net.DatagramPackets</code>。</li>
<li><a title="java.net 中的类" href="http://gceclub.sun.com.cn/Java_Docs/html/zh_CN/api/java/net/MulticastSocket.html"><code>MulticastSocket</code></a> 是 DatagramSocket 的子类，在处理多播组时使用。</li>
</ul>
<p>使用 TCP 套接字的发送和接收操作需要借助 InputStream 和 OutputStream 来完成，这两者是通过 java.net.Socket.getInputStream 和 java.net.Socket.getOutputStream 方法获取的。</p>
<h4>高级API</h4>
<p>java.net 包中的许多类可以提供更加高级的抽象，允许方便地访问网络上的资源。这些类为：</p>
<ul>
<li><a title="java.net 中的类" href="http://gceclub.sun.com.cn/Java_Docs/html/zh_CN/api/java/net/URI.html"><code>URI</code></a> 是表示在 RFC 2396 中指定的统一资料标识符的类。顾名思义，它只是一个标识符，不直接提供访问资源的方法。</li>
<li><a title="java.net 中的类" href="http://gceclub.sun.com.cn/Java_Docs/html/zh_CN/api/java/net/URL.html"><code>URL</code></a> 是表示统一资源定位符的类，它既是 URI 的旧式概念又是访问资源的方法。</li>
<li><a title="java.net 中的类" href="http://gceclub.sun.com.cn/Java_Docs/html/zh_CN/api/java/net/URLConnection.html"><code>URLConnection</code></a> 是根据 URL 创建的，是用于访问 URL 所指向资源的通信链接。此抽象类将大多数工作委托给底层协议处理程序，如 http 或 ftp。</li>
<li><a title="java.net 中的类" href="http://gceclub.sun.com.cn/Java_Docs/html/zh_CN/api/java/net/HttpURLConnection.html"><code>HttpURLConnection</code></a> 是 URLConnection 的子类，提供一些特定于 HTTP 协议的附加功能。</li>
</ul>
<p>建议的用法是使用 <a title="java.net 中的类" href="http://gceclub.sun.com.cn/Java_Docs/html/zh_CN/api/java/net/URI.html"><code>URI</code></a> 指定资源，然后在访问资源时将其转换为 <a title="java.net 中的类" href="http://gceclub.sun.com.cn/Java_Docs/html/zh_CN/api/java/net/URL.html"><code>URL</code></a>。从该 URL 可以获取 <a title="java.net 中的类" href="http://gceclub.sun.com.cn/Java_Docs/html/zh_CN/api/java/net/URLConnection.html"><code>URLConnection</code></a> 以进行良好控制，也可以直接获取 InputStream。</p>
<p>下面是一个示例：</p>
<pre class="brush: java;">
URI uri = new URI(&quot;http://java.sun.com/&quot;);
URL url = uri.toURL();
InputStream in = url.openStream();
</pre>
<h4>URLConnection 和 HttpURLConnection 的使用：</h4>
<p>抽象类 URLConnection 是所有表示应用程序与 URL 之间通信链路的类的超类。该类的实例可以用来对由 URL 引用的资源进行读取和写入操作</p>
<p>HttpURLConnection 仅是支持了 HTTP 特定功能的 URLConnection</p>
<ol>
<li>通过调用 URL 的 <code>openConnection</code> 方法产生一连接对象。</li>
<li>操纵设置参数和一般请求属性。</li>
<li>使用 <code>connect</code> 方法，实现对远程对象的实际连接。</li>
<li>远程对象一旦可用，就可以访问远程对象的域和内容。</li>
</ol>
<p>通过如下的方法修改设置参数：</p>
<ul><code> </code></p>
<li>setAllowUserInteraction</li>
<li>setDoInput</li>
<li>setDoOutput</li>
<li>setIfModifiedSince</li>
<li>setUseCaches</li>
</ul>
<p>通过使用如下的方法修改一般请求属性：</p>
<ul><code> </code></p>
<li>setRequestProperty</li>
</ul>
<p><code>AllowUserInteraction</code> 和 <code>UseCaches</code> 参数的缺省值可以通过使用 <code>setDefaultAllowUserInteraction</code> 和 <code>setDefaultUseCaches</code> 方法来设置。 而一般请求属性的缺省值可以通过方法 <code>setDefaultRequestProperty</code> 来设置 。</p>
<p>上面的每个 <code>set</code> 方法都有相应 <code>get</code> 方法来获取参数和一般请求属性的值。可用的特定参数和一般请求属性是特定于协议的。</p>
<p>对远程对象的连接完成后，用下列方法访问报头域和内容：</p>
<ul><code> </code></p>
<li>getContent</li>
<li>getHeaderField</li>
<li>getInputStream</li>
<li>getOutputStream</li>
</ul>
<p>确认报头域能够被频繁访问。方法：</p>
<ul><code> </code></p>
<li>getContentEncoding</li>
<li>getContentLength</li>
<li>getContentType</li>
<li>getDate</li>
<li>getExpiration</li>
<li>getLastModified</li>
</ul>
<p>提供对这些域的便利访问。 <code>getContentType</code> 方法由 <code>getContent</code> 方法调用以确定远程对象的类型； 子类来覆盖方法 <code>getContentType</code> 可能是有利的。</p>
<p>下面是一个通过Twitter API去获信息的demo：</p>
<pre class="brush: java;">
        URL url = new URL(&quot;http://t.bbercn.com/statuses/user_timeline.xml&quot;);
        String username = (String) params[0];
        String password = (String) params[1];
        String user_paw = username + &quot;:&quot; + password;
        String encoding = &quot;Basic &quot; + Base64Converter.encode(user_paw.getBytes());
        URLConnection uc = url.openConnection();
        uc.setRequestProperty(&quot;Authorization&quot;, encoding);
        InputStream content = (InputStream) uc.getInputStream();
</pre>
<p>剩下的工作就是对InputStream 进行本地处理，Twitter返回的是XML，那么我们下面就对XML进行解析，获取我们要获取的信息。</p>
<h3>XML Parser</h3>
<p>关于 xml 解析的工具有很多，具体可以看这里：http://www.open-open.com/31.htm 罗列的一些。</p>
<p>下面通过Commons-Digester来处理上面我们获取的InputStream</p>
<pre class="brush: java;">
public class ParseTools {

    private List statuses = new ArrayList&lt;Status&gt;();

    public List&lt;Status&gt; getStatuses() {
        Collections.sort(statuses);
        return statuses;
    }

    public void parseStatus(InputStream stream) throws IOException, SAXException {
        Digester digester = new Digester();
        digester.setValidating(false);
        digester.push(this);

        digester.addObjectCreate(&quot;statuses/status&quot;, Status.class);
        //status
        digester.addBeanPropertySetter(&quot;statuses/status/id&quot;);
        digester.addBeanPropertySetter(&quot;statuses/status/created_at&quot;);
        digester.addBeanPropertySetter(&quot;statuses/status/text&quot;);
        digester.addBeanPropertySetter(&quot;statuses/status/source&quot;);
        digester.addBeanPropertySetter(&quot;statuses/status/truncated&quot;);
        digester.addBeanPropertySetter(&quot;statuses/status/in_reply_to_status_id&quot;);
        digester.addBeanPropertySetter(&quot;statuses/status/in_reply_to_user_id&quot;);
        digester.addBeanPropertySetter(&quot;statuses/status/favorited&quot;);
        digester.addBeanPropertySetter(&quot;statuses/status/in_reply_to_screen_name&quot;);
        //user
        digester.addObjectCreate(&quot;statuses/status/user&quot;, User.class);
        digester.addBeanPropertySetter(&quot;statuses/status/user/id&quot;);
        digester.addBeanPropertySetter(&quot;statuses/status/user/name&quot;);
        digester.addBeanPropertySetter(&quot;statuses/status/user/screen_name&quot;);
        digester.addBeanPropertySetter(&quot;statuses/status/user/description&quot;);
        digester.addBeanPropertySetter(&quot;statuses/status/user/location&quot;);
        digester.addBeanPropertySetter(&quot;statuses/status/user/profile_image_url&quot;);
        digester.addBeanPropertySetter(&quot;statuses/status/user/url&quot;);
        digester.addBeanPropertySetter(&quot;statuses/status/user/isProtected&quot;);
        digester.addBeanPropertySetter(&quot;statuses/status/user/followers_count&quot;);
        digester.addBeanPropertySetter(&quot;statuses/status/user/friends_count&quot;);
        digester.addSetNext(&quot;statuses/status/user&quot;, &quot;setUser&quot;);
        digester.addSetNext(&quot;statuses/status&quot;, &quot;addStatuses&quot;, Status.class.getName());
        digester.parse(stream);
    }

    public void addStatuses(Status status) {
        Status d = new Status();
        d.setId(status.getId());
        d.setCreated_at(status.getCreated_at());
        d.setFavorited(status.isFavorited());
        d.setText(status.getText());
        d.setSource(status.getSource());
        d.setTruncated(status.isTruncated());
        d.setIn_reply_to_screen_name(status.getIn_reply_to_screen_name());
        d.setIn_reply_to_status_id(status.getIn_reply_to_status_id());
        d.setIn_reply_to_user_id(status.getIn_reply_to_user_id());
        d.setUser(status.getUser());
        getStatuses().add(d);
    }
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.quanlei.com/2009/12/java-net-and-xml-parser/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>周主题推迟一周</title>
		<link>http://www.quanlei.com/2009/12/week-subject-delay-a-week/</link>
		<comments>http://www.quanlei.com/2009/12/week-subject-delay-a-week/#comments</comments>
		<pubDate>Mon, 14 Dec 2009 08:47:46 +0000</pubDate>
		<dc:creator>小权</dc:creator>
				<category><![CDATA[周主题]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[xml]]></category>
		<category><![CDATA[主题]]></category>
		<category><![CDATA[任务]]></category>
		<category><![CDATA[公司]]></category>
		<category><![CDATA[培训]]></category>
		<category><![CDATA[忙]]></category>
		<category><![CDATA[项目]]></category>

		<guid isPermaLink="false">http://www.quanlei.com/?p=1070</guid>
		<description><![CDATA[由于最近另一个项目的启动，工作方面基本上是掐着时间在忙，所以周主题的任务就只能稍微往后推一周了。 预计本周四结合公司的培训内容，出一个有关JQuery的入门介绍，这个内容顺便就补给上周的周主题。 顺便预告下：接下来这周和下周会整理有关Java.Net包下一些常用类的使用，包括HttpClient的使用，以及XML Parser方面的汇总。]]></description>
			<content:encoded><![CDATA[<p><span style="font-size: xx-large;"><span style="color: #800000;">由</span></span>于最近另一个项目的启动，工作方面基本上是掐着时间在忙，所以周主题的任务就只能稍微往后推一周了。</p>
<p>预计本周四结合公司的培训内容，出一个有关JQuery的入门介绍，这个内容顺便就补给上周的周主题。</p>
<p>顺便预告下：接下来这周和下周会整理有关Java.Net包下一些常用类的使用，包括HttpClient的使用，以及XML Parser方面的汇总。</p>
]]></content:encoded>
			<wfw:commentRss>http://www.quanlei.com/2009/12/week-subject-delay-a-week/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>[09/49周主题] – Swing Tips</title>
		<link>http://www.quanlei.com/2009/12/0949-week-subject-swing/</link>
		<comments>http://www.quanlei.com/2009/12/0949-week-subject-swing/#comments</comments>
		<pubDate>Fri, 04 Dec 2009 12:35:17 +0000</pubDate>
		<dc:creator>小权</dc:creator>
				<category><![CDATA[周主题]]></category>
		<category><![CDATA[编程相关]]></category>
		<category><![CDATA[AWT]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[NetBeans]]></category>
		<category><![CDATA[Swing]]></category>
		<category><![CDATA[UI]]></category>
		<category><![CDATA[客户]]></category>
		<category><![CDATA[插件]]></category>
		<category><![CDATA[界面]]></category>
		<category><![CDATA[设计]]></category>

		<guid isPermaLink="false">http://www.quanlei.com/?p=974</guid>
		<description><![CDATA[选择这个主题，是因为上周公司刚好做了一个有关“Beginning Java AWT and Swing” 的培训，借此机会正好总结一下这方面的使用技巧。对于Swing界面方面的研究，我仅仅是应用而已，公司里有几位同事在这方面的研究比较深，这块的应用和使用技巧分两部分， 一部分是Swing 使用本身的，另一部分是Design工具NetBeans的，如果是刚入门建议从这里看起：Creating a GUI With JFC/Swing。 本期主题：Swing Tips 一、性能问题 随着Java 6对于Swing性能的改进，Swing的运行速度已经开始得到了大大的提高，看看NetBeans就知道了，NetBeans就是Swing开发的，如果你跑Swing很慢，很耗资源，那么应该从自己的程序上找找问题，推荐使用NetBeans自带的Profile查找原因，教程在这里 &#8211; Profile Introduce 。 二、LookAndFeel 用Swing做企业应用时，LookAndFeel的选择和使用是决定这个项目能否被客户接受的一个很大因素，即要好看，又要考虑跨平台的兼容性，必要时自己还得设计部分LookAndFeel， 可以看看这里提供的一些开源LookAndFeel：http://www.open-open.com/61.htm 和http://www.javootoo.com/。 切换LookAndFeel： UIManager.setLookAndFeel(LookAndFeelName); SwingUtilities.updateComponentTreeUI(frame); frame.pack(); 三、合理的控制初始化组件和组件初始化的顺序可以很大的提高性能 举个例子：之前我们项目中有一个地方，当打开程序时，会初始化几十个甚至成百个JPanel，这显然成为程序启动时慢的一个因素，也导致了用户体验的降低，这些JPanel完全可以在程序启动后再根据用户的需要去初始化，因为用户打开程序时这些Panel不是必须看到的。 四、要有统一的UI规范 比如Button的高度，进度条的高宽等，也可以通过UIManager给系统组件设置统一属性，比如统一设定Button的间距和字体： UIManager.put(&#34;Button.margin&#34;, new Insets(2, 5, 2, 5)); UIManager.put(&#34;Button.font&#34;, new Font(&#34;宋体&#34;, Font.PLAIN, 13)); 五、多线程的使用 用Swing做的都是界面的东西，如果界面假死或者用户等待事件太长，那么用户体验必然是不好的，这里就需要用到多线程的使用了，当界面处理一个请求时，不能让界面假死了，需要后台另一个线程去做处理，然后将结果返回到Swing线程，这块可以看看SwingWorker的介绍。 六、布局管理器 布局管理器的使用在Swing里面是比较重要的，它直接决定了你界面的显示效果，也是比较难用的一块，不好举例子，建议多了解每个布局管理器的使用场景。 七、JTable &#38; JTree 在Swing组件的使用中除了布局管理器，估计就数JTable和JTree的使用稍微有点麻烦了，下面我就分享一些实际项目中JTable的一些实例，关于JTree，可以点这里：JTree 经验 总结 。 [...]]]></description>
			<content:encoded><![CDATA[<p><span style="color: #800000;"><span style="font-size: xx-large;">选</span></span>择这个主题，是因为上周公司刚好做了一个有关“Beginning Java AWT and Swing” 的培训，借此机会正好总结一下这方面的使用技巧。对于Swing界面方面的研究，我仅仅是应用而已，公司里有几位同事在这方面的研究比较深，这块的应用和使用技巧分两部分， 一部分是Swing 使用本身的，另一部分是Design工具NetBeans的，如果是刚入门建议从这里看起：<a href="http://java.sun.com/docs/books/tutorial/uiswing/index.html" target="_blank">Creating a GUI With JFC/Swing</a>。</p>
<h2>本期主题：Swing Tips</h2>
<h3>一、性能问题</h3>
<blockquote><p>随着Java 6对于Swing性能的改进，Swing的运行速度已经开始得到了大大的提高，看看NetBeans就知道了，NetBeans就是Swing开发的，如果你跑Swing很慢，很耗资源，那么应该从自己的程序上找找问题，推荐使用NetBeans自带的Profile查找原因，教程在这里 &#8211; <a href="http://zh-cn.netbeans.org/kb/60/java/profiler-intro.html" target="_blank">Profile Introduce</a> 。</p></blockquote>
<h3>二、LookAndFeel</h3>
<blockquote><p>用Swing做企业应用时，LookAndFeel的选择和使用是决定这个项目能否被客户接受的一个很大因素，即要好看，又要考虑跨平台的兼容性，必要时自己还得设计部分LookAndFeel， 可以看看这里提供的一些开源LookAndFeel：http://www.open-open.com/61.htm 和http://www.javootoo.com/。<br />
切换LookAndFeel：</p>
<pre class="brush: java;">
UIManager.setLookAndFeel(LookAndFeelName);
SwingUtilities.updateComponentTreeUI(frame);
frame.pack();
</pre>
</blockquote>
<h3>三、合理的控制初始化组件和组件初始化的顺序可以很大的提高性能</h3>
<blockquote><p>举个例子：之前我们项目中有一个地方，当打开程序时，会初始化几十个甚至成百个JPanel，这显然成为程序启动时慢的一个因素，也导致了用户体验的降低，这些JPanel完全可以在程序启动后再根据用户的需要去初始化，因为用户打开程序时这些Panel不是必须看到的。</p></blockquote>
<h3>四、要有统一的UI规范</h3>
<blockquote><p>比如Button的高度，进度条的高宽等，也可以通过UIManager给系统组件设置统一属性，比如统一设定Button的间距和字体：</p>
<pre class="brush: java;">
UIManager.put(&quot;Button.margin&quot;, new Insets(2, 5, 2, 5));
UIManager.put(&quot;Button.font&quot;, new Font(&quot;宋体&quot;, Font.PLAIN, 13));
</pre>
</blockquote>
<h3>五、多线程的使用</h3>
<blockquote><p>用Swing做的都是界面的东西，如果界面假死或者用户等待事件太长，那么用户体验必然是不好的，这里就需要用到多线程的使用了，当界面处理一个请求时，不能让界面假死了，需要后台另一个线程去做处理，然后将结果返回到Swing线程，这块可以看看<a href="http://java.sun.com/javase/6/docs/api/javax/swing/SwingWorker.html" target="_blank">SwingWorker</a>的介绍。</p></blockquote>
<h3>六、布局管理器</h3>
<blockquote><p>布局管理器的使用在Swing里面是比较重要的，它直接决定了你界面的显示效果，也是比较难用的一块，不好举例子，建议多了解每个布局管理器的使用场景。</p></blockquote>
<h3>七、JTable &amp; JTree</h3>
<blockquote><p>在Swing组件的使用中除了布局管理器，估计就数JTable和JTree的使用稍微有点麻烦了，下面我就分享一些实际项目中JTable的一些实例，关于JTree，可以点这里：<a href="http://www.google.cn/search?hl=zh-CN&amp;newwindow=1&amp;q=JTree+%E7%BB%8F%E9%AA%8C+%E6%80%BB%E7%BB%93" target="_blank">JTree 经验 总结</a> 。</p>
<h4>JTable相关</h4>
<h5>1、自定义表头排序</h5>
<pre class="brush: java;">
TableRowSorter rs = (TableRowSorter) table.getRowSorter();
Comparator&lt;Integer&gt; intComparator = new Comparator&lt;Integer&gt;() {

            public int compare(Integer o1, Integer o2) {
                return o1.compareTo(o2);
            }
        };
rs.setComparator(3, intComparator);
 </pre>
<h5>2、自定义Table Renderer</h5>
<pre class="brush: java;">
public class CommonTableCellRenderer extends DefaultTableCellRenderer {

        @Override
        public Component getTableCellRendererComponent(JTable table, Object value,
                boolean isSelected, boolean cellHasFocus, int row, int column) {
            JComponent comp = (JComponent) super.getTableCellRendererComponent(table, value,
isSelected, cellHasFocus, row, column);
            //表格的奇数偶数行交叉颜色显示
            if (!isSelected) {
                if (row % 2 == 0) {
                    comp.setBackground(UIConsts.HIGHLIGHTER_COLOR);
                } else {
                    comp.setBackground(Color.white);
                }
            }

            //table column里面显示图标和对齐方式
            switch (column) {
                case PaperTableModel.STATUS_COLUMN:
                    switch ((EntityStatus) value) {
                        case VALID:
                            comp.setIcon(ENABLED_ICON);
                            setHorizontalAlignment(JLabel.LEADING);
                            break;
                        case DISABLED:
                            comp.setIcon(DISABLED_ICON);
                            setHorizontalAlignment(JLabel.CENTER);
                            break;
                    }
                    break;
                default:
                    comp.setIcon(null);
                    break;
            }

            return comp;
        }
    }
 </pre>
<h5>3、自定义Table列宽</h5>
<pre class="brush: java;">
TableColumnModel colModel = table.getColumnModel();
colModel.getColumn(0).setPreferredWidth(70);
colModel.getColumn(1).setPreferredWidth(55);
colModel.getColumn(2).setPreferredWidth(120);
</pre>
<h5>4、禁止Table列拖动</h5>
<pre class="brush: java;"> table.getTableHeader().setReorderingAllowed(false);  </pre>
<h5>5、单选表格设置</h5>
<pre class="brush: java;"> table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);   </pre>
<h5>6、设置表头默认支持排序</h5>
<pre class="brush: java;"> table.setAutoCreateRowSorter(true);  </pre>
<h5>7、设置列不可随容器组件大小变化自动调整宽度</h5>
<pre class="brush: java;"> table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);  </pre>
<h5>8、固定Table上的某些列不滚动</h5>
<p>这个需求是这样的，比如Table上左边有部分数据，是后面数据所共有的属性，那么当后面数据很多时，显示不下会出现滚动条，但是滚动时又不想让左侧的共有属性动，只滚动右侧的数据部分。<br />
实现原理是:scrollPane里面放置一个表格，然后在scrollPane的左上角放置以共有属性的部分为Model的表格，剩下的右侧就是剩余的纯数据表格。<br />
最终效果就是表格左侧的列锁定了，右侧数据出现滚动条时，可以滚动，但左侧不动。<br />
核心代码：比如有HeaderTable和ReportTable， 其中ReportTable是放置在一个ScrollPanel里面，Model是所有数据的Model，将左侧的数据和右侧的数据分开</p>
<pre class="brush: java;">
//找到主表所在的scrollPane
JScrollPane scrollPane = (JScrollPane) SwingUtilities.
   getAncestorOfClass(JScrollPane.class,
    reportTable.getTable());

//中间处理headerTable的数据和reportTable剩余的数据

//将新表HeaderTable放在scrollPane的左上角
scrollPane.setRowHeaderView(headerTable.getTable());
scrollPane.setCorner(JScrollPane.UPPER_LEFT_CORNER,
                    headerTable.getTable().getTableHeader());
</pre>
<h5>9、Table上的直接编辑功能</h5>
<p>两点：<br />
1、重写 public boolean isCellEditable(int row, int columnIndex) 方法，定义可编辑的行列。<br />
2、重写 public void setValueAt(Object obj, int rowIndex, int columnIndex) 方法，拿到原来的对象，设置新的对象值。</p>
<h5>10、Table的Excel导出功能</h5>
<p>表格上的Excel导出功能还是比较实用的功能，企业应用一般都会用到，这里提供相关代码</p>
<pre class="brush: java;">
try {
   WritableCellFormat titleFormat = new WritableCellFormat(
   new WritableFont(WritableFont.createFont(&quot;黑体&quot;), 16,
   WritableFont.NO_BOLD));
   titleFormat.setVerticalAlignment(VerticalAlignment.CENTRE); // 垂直对齐
   titleFormat.setAlignment(Alignment.CENTRE); // 水平对齐
   titleFormat.setWrap(true); // 是否换行

   WritableCellFormat headerFormat = new WritableCellFormat();
   headerFormat.setBorder(Border.ALL, BorderLineStyle.THIN); // 线条
   headerFormat.setVerticalAlignment(VerticalAlignment.CENTRE); // 垂直对齐
   headerFormat.setAlignment(Alignment.CENTRE); // 水平对齐
   headerFormat.setWrap(true); // 是否换行

   WritableCellFormat countFormat = new WritableCellFormat(
   new NumberFormat(&quot;0.000&quot;));
   countFormat.setBorder(Border.ALL, BorderLineStyle.THIN); // 线条
   countFormat.setVerticalAlignment(VerticalAlignment.CENTRE); // 垂直对齐
   countFormat.setAlignment(Alignment.RIGHT); // 水平对齐
   countFormat.setWrap(true); // 是否换行

   WritableCellFormat moneyFormat = new WritableCellFormat(
   new NumberFormat(&quot;0.00&quot;));
   moneyFormat.setBorder(Border.ALL, BorderLineStyle.THIN); // 线条
   moneyFormat.setVerticalAlignment(VerticalAlignment.CENTRE); // 垂直对齐
   moneyFormat.setAlignment(Alignment.RIGHT); // 水平对齐
   moneyFormat.setWrap(true); // 是否换行

   WritableCellFormat intFormat = new WritableCellFormat(
   new NumberFormat(&quot;0&quot;));
   intFormat.setBorder(Border.ALL, BorderLineStyle.THIN); // 线条
   intFormat.setVerticalAlignment(VerticalAlignment.CENTRE); // 垂直对齐
   intFormat.setAlignment(Alignment.RIGHT); // 水平对齐
   intFormat.setWrap(true); // 是否换行

   WritableWorkbook book = Workbook.createWorkbook(exportFile);
   WritableSheet sheet = book.createSheet(&quot;综合统计报表&quot;, 0);
   int titleRow = 0;
   int headerRow = 3;
   int dataRow = 5;
   sheet.mergeCells(0, titleRow, model.getColumnCount() - 1,
   titleRow);
   Label titleLab = new Label(0, titleRow, tableTitleTxfd.getText(), titleFormat);
   sheet.addCell(titleLab);

   //生成表头
   for (int j = 0; j &lt; model.getColumnCount(); j++) {
       sheet.mergeCells(j, headerRow, j, headerRow + 1);
       Label lab = new Label(j, headerRow, model.getColumnName(
      j), headerFormat);
       sheet.addCell(lab);
   }

   for (int row = 0; row &lt; model.getRowCount(); row++) {
       for (int col = 0; col &lt; model.getColumnCount(); col++) {
          Object obj = model.getValueAt(row, col);
          if (obj instanceof String) {
             Label lab = new Label(col, dataRow + row,
               (String) obj, headerFormat);
            sheet.addCell(lab);
          } else if (obj instanceof Integer) {
         Number labelN = new Number(col, dataRow
         + row, (Integer) obj, intFormat);
         sheet.addCell(labelN);
         } else {
         Label lab =
         new Label(col, dataRow + row, &quot;&quot;,
         headerFormat);
         sheet.addCell(lab);
         }
      }
   }

   //生成表尾
   int footerRow = dataRow + model.getRowCount() + 1;
   int step =
   (int) (((double) (model.getColumnCount() - 2) / 3)
   + 1);
   Label footerLab = new Label(0, footerRow, &quot;部门负责人：&quot;);
   sheet.addCell(footerLab);
   footerLab = new Label(step, footerRow, &quot;制表：&quot; + creatorTxfd.getText());
   sheet.addCell(footerLab);
   footerLab = new Label(model.getColumnCount() - 2, footerRow,
   NazcaFormater.getSimpleDateString(new Date()));
   sheet.addCell(footerLab);

   sheet.setColumnView(0, 16);
   sheet.setRowView(titleRow, 600);

   book.write();
   book.close();
   //导出成功
   } catch (Throwable ex) {
   //导出报表失败
   ex.printStackTrace();
}
</pre>
<h5>11、Table的打印功能</h5>
<p>打印这块，之前已经提过，可以参考之前的文章 <a href="http://www.quanlei.com/2009/11/jtable_print/">JTable Print</a></p>
<h5>12、在Table上选择多行</h5>
<pre class="brush: java;">
int rowcounts=table.getSelectedRows().length;
if(rowcounts&gt;1)
  int[] rows=table.getSelectedRows();
    for(int i=0;i&lt;rows.length;i++){
    String value=(String) tableModel.getValueAt(i, 1);
  }
}
</pre>
</blockquote>
<h2>NetBeans 6+ Tips</h2>
<p>这里说NetBeans，主要是因为目前Swing开发方面，还没有哪个IDE能胜过NetBeans。</p>
<blockquote><p>一、NetBeans的配置</p>
<blockquote><p>1、配置为英文，大部分时间我们下载的都是中文的版本，可以通过在/$NetBeans_HOME/etc/netbeans.conf中添加 &#8211;locale en_US， 让启动时显示为英文，这个之前也有文章介绍：<a href="http://www.quanlei.com/tag/netbeans-%E8%8B%B1%E6%96%87%E7%95%8C%E9%9D%A2/" target="_blank">Netbeans 英文界面</a> 和 <a href="http://www.quanlei.com/2009/07/%E8%A1%A5%E5%8F%91%EF%BC%9A%E6%9C%80%E7%AE%80%E5%8D%95%E7%9A%84netbeans%E4%B8%AD%E8%8B%B1%E6%96%87%E5%88%87%E6%8D%A2/" target="_blank">最简单的Netbeans中英文切换</a><br />
2、优化配置可以看之前介绍的这篇文章，就不重复了：<a href="http://www.quanlei.com/2008/12/netbeans-65-%E4%BC%98%E5%8C%96%E5%BB%BA%E8%AE%AE/" target="_blank">Netbeans 6.5 优化建议 </a></p></blockquote>
<p>二、经验分享</p>
<blockquote><p>1、Swing的Debug虽然被很多人说不好用，但是在用NetBeans时，多用Debug可以提高效率，因为Debug模式下的修改，大部分只要点击应用，就可以不用重启项目而看到效果。<br />
2、很好用的快捷键和快速补齐(限Windows + Linux下，如果在Mac下改成 ⌘ 试试)，如：</p>
<blockquote>
<pre>快捷键：
Ctrl+R          Rename
Alt+Enter       Fix Error(Eclipse Ctrl+1)
Alt+Shift+F    Quick Format
Alt+Shift+I     Fix Import
F9                Build File
F6                Run Main Project
Shift+F6        Run File
Ctrl+|           Insert Code

快速补齐（英文输入状态下，输入完后按Tab键，也可以自己配置为其他键，在Options - Editor -
Code Templates下）：
psvm            public static void main
sout             System.out.println
im               implements
Psfs             public static final String
psfi             private static final String
fore            for($ : $){}
fori             for(int i = 0; i &lt; arr.length; i++){}
forl             for(int i = 0; i &lt; list.size(); i++){}</pre>
</blockquote>
</blockquote>
<p>三、插件分享<br />
我们都知道NetBeans上的插件很多，可以说NetBeans正是因为这些插件才强大起来，支持的功能也更多了。分享的这几个插件是平时工作时，可以显著提高效率的，不好的不推荐，你如果有好的也别忘记分享下。</p>
<blockquote><p>1、Path Tools  &#8211; 可以直接查找到类或者文件夹所在的磁盘位置，基本是我每次装完NetBeans的后第一个装的插件。<br />
2、SQE(Software Quality Environment) &#8211; 是最近同事刚刚推荐的一个插件，看名字就知道了，是一个类似Firebug的插件，可以发现程序中存在的一些显著的错误，很不错。<br />
3、<a href="http://plugins.netbeans.org/PluginPortal/faces/PluginDetailPage.jsp?pluginid=9000" target="_blank">UUID Generator </a>- 同事写的一个快速生成UUID的插件。<br />
4、SwingX 插件 &#8211; 用来添加一些SwingX组件的。<br />
5、iReport &#8211; 打印报表用的插件，结合JasperReport使用。</p></blockquote>
</blockquote>
]]></content:encoded>
			<wfw:commentRss>http://www.quanlei.com/2009/12/0949-week-subject-swing/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>[09/48周主题] &#8211; JPA</title>
		<link>http://www.quanlei.com/2009/11/0948-week-subject-jpa/</link>
		<comments>http://www.quanlei.com/2009/11/0948-week-subject-jpa/#comments</comments>
		<pubDate>Tue, 24 Nov 2009 12:35:22 +0000</pubDate>
		<dc:creator>小权</dc:creator>
				<category><![CDATA[周主题]]></category>
		<category><![CDATA[编程相关]]></category>
		<category><![CDATA[API]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[JPA]]></category>
		<category><![CDATA[对象]]></category>
		<category><![CDATA[总结]]></category>

		<guid isPermaLink="false">http://www.quanlei.com/?p=879</guid>
		<description><![CDATA[这是本博客开始周主题的第一个主题，周主题计划按自然周为标记，记录一年内每周的关注主题，这样至少可以提醒自己哪个周的没有写了。 本期主题：JPA 对于JPA不熟悉的朋友可以先看看这里：百度百科之JPA 里面介绍了JPA的起源，优势，厂商等。 本文是由网上其他网友的经验和自己的经验总结而成，个人能力有限，不免有错误之处，如有误导之地恳请指正。欢迎大家提出宝贵意见，以便完善。 一、JPA中必须知道的4个状态 1. 新建态(New)：新创建的实例对象，没有持久化主键。 简单讲就是你刚new出来的对象，谁也管不着的。 2. 受控态(Managed)：在持久化上下文中受管理的对象； 先理解两个概念持久化主键和持久化上下文：持久化上下文是由与该上下文相关联的 EntityManager 实例管理的一组实体实例，关键词是EntityManager， 新创建的实体尚未被托管于持久化上下文中，EntityManager无法对它进行管理。EntityManager对持久化上下文中的实体进行管理，必然通过主键去查找实体对象，这个主键就是持久化主键。 3. 游离态(Detached)：游离于持久化上下文之外的实例对象； 4. 删除态(Removed)：被删除的实例对象。 这些状态通过调用EntityManager的接口方法进行相互迁移 二、EntityManager 的常用API void persist(Object entity) 通过persist()方法，新建状态将转换为受控状态。这意谓着当persist ()方法所在的事务提交时，实体的数据将保存到数据库中。 如果实体已经被持久化，那么再调用persist()操作，会抛出异常 Duplicate entry。 如果对一个已经删除的实体调用persist()操作，删除态的实体又转变为受控态，实体的数据将保存到数据库中。 如果persist的是一个游离实体（即上下文中没有它），而上下文中又没有它的受管版本，数据库却有这个实体，那么会抛出异常 Duplicate entry； 如果persist的是一个游离实体（即上下文中没有它），而上下文中却有它的受管版本，数据库中也有了这个实体，那么EntityManager在persist它的时候就会抛出异常：javax.persistence.EntityExistsException 在一个实体上调用persist()操作，将广播到和实体关联的其他实体上，执行相应的级联持久化操作； void remove(Object entity) 通过remove()方法删除一个受控的实体; 如果实体声明为级联删除(cascade=REMOVE 或者cascade=ALL )，被关联的实体也会被删除; 在一个新建状态的实体上调用remove()操作，将被忽略; 如果在游离实体上调用remove()操作，将抛出 IllegalArgumentException，相关的事务将回滚; 如果在已经删除的实体上执行remove()操作，也会被忽略 T merge(T entity) 将一个游离态的实体持久化到数据库中，并转换为受控态的实体； Merge一个游离版本，同时上下文中却有它的受管版本，那么返回的是受管版本，数据库中的数据更新 Query createQuery(String qlString) [...]]]></description>
			<content:encoded><![CDATA[<p><span style="color: #800000;"><span style="font-size: xx-large;">这</span></span>是本博客开始周主题的第一个主题，周主题计划按自然周为标记，记录一年内每周的关注主题，这样至少可以提醒自己哪个周的没有写了。</p>
<h2>本期主题：JPA</h2>
<blockquote><p>对于JPA不熟悉的朋友可以先看看这里：<a href="http://baike.baidu.com/view/1036852.htm?fr=ala0" target="_blank">百度百科之JPA</a> 里面介绍了JPA的起源，优势，厂商等。</p></blockquote>
<p><strong>本文是由网上其他网友的经验和自己的经验总结而成，个人能力有限，不免有错误之处，如有误导之地恳请指正。欢迎大家提出宝贵意见，以便完善。</strong><br />
<img class="aligncenter size-full wp-image-892" title="context" src="http://www.quanlei.com/wp-content/uploads/2009/11/context.jpg" alt="context" width="257" height="256" /></p>
<h3>一、JPA中必须知道的4个状态</h3>
<blockquote>
<h4>1. 新建态(New)：新创建的实例对象，没有持久化主键。</h4>
<blockquote><p>简单讲就是你刚new出来的对象，谁也管不着的。</p></blockquote>
<h4>2. 受控态(Managed)：在持久化上下文中受管理的对象；</h4>
<blockquote><p>先理解两个概念<strong>持久化主键</strong>和<strong>持久化上下文</strong>：持久化上下文是由与该上下文相关联的 EntityManager 实例管理的一组实体实例，关键词是EntityManager， 新创建的实体尚未被托管于持久化上下文中，EntityManager无法对它进行管理。EntityManager对持久化上下文中的实体进行管理，必然通过主键去查找实体对象，这个主键就是持久化主键。</p></blockquote>
<h4>3. 游离态(Detached)：游离于持久化上下文之外的实例对象；</h4>
<h4>4. 删除态(Removed)：被删除的实例对象。</h4>
</blockquote>
<p>这些状态通过调用EntityManager的接口方法进行相互迁移</p>
<h3>二、EntityManager 的常用API</h3>
<blockquote>
<h4>void persist(Object entity)</h4>
<blockquote>
<ul>
<li>通过persist()方法，新建状态将转换为受控状态。这意谓着当persist ()方法所在的事务提交时，实体的数据将保存到数据库中。</li>
<li>如果实体已经被持久化，那么再调用persist()操作，会抛出异常 Duplicate entry。</li>
<li>如果对一个已经删除的实体调用persist()操作，删除态的实体又转变为受控态，实体的数据将保存到数据库中。</li>
<li>如果persist的是一个游离实体（即上下文中没有它），而上下文中又没有它的受管版本，数据库却有这个实体，那么会抛出异常 Duplicate entry；</li>
<li>如果persist的是一个游离实体（即上下文中没有它），而上下文中却有它的受管版本，数据库中也有了这个实体，那么EntityManager在persist它的时候就会抛出异常：javax.persistence.EntityExistsException</li>
<li>在一个实体上调用persist()操作，将广播到和实体关联的其他实体上，执行相应的级联持久化操作；</li>
</ul>
</blockquote>
<h4>void remove(Object entity)</h4>
<blockquote>
<ul>
<li>通过remove()方法删除一个受控的实体;</li>
<li>如果实体声明为级联删除(cascade=REMOVE 或者cascade=ALL )，被关联的实体也会被删除;</li>
<li>在一个新建状态的实体上调用remove()操作，将被忽略;</li>
<li>如果在游离实体上调用remove()操作，将抛出 IllegalArgumentException，相关的事务将回滚;</li>
<li>如果在已经删除的实体上执行remove()操作，也会被忽略</li>
</ul>
</blockquote>
<h4>T merge(T entity)</h4>
<blockquote>
<ul>
<li>将一个游离态的实体持久化到数据库中，并转换为受控态的实体；</li>
<li>Merge一个游离版本，同时上下文中却有它的受管版本，那么返回的是受管版本，数据库中的数据更新</li>
</ul>
</blockquote>
<h4>Query createQuery(String qlString)</h4>
<blockquote>
<ul>
<li>根据JPA的查询语句创建一个查询对象Query</li>
</ul>
</blockquote>
<h4>T find(Class entityClass, Object primaryKey)</h4>
<blockquote>
<ul>
<li>以主键查询实体对象，entityClass是实体的类，primaryKey是主键值</li>
</ul>
</blockquote>
</blockquote>
<h3>三、使用时应注意的一些情况</h3>
<blockquote><p>1. EntityManager对象的事务管理方式有两种，分别为JTA和RESOURCE_LOCAL，即Java Transaction API方法和本地的事务管理。JPA中的事务类型通过persistence.xml文件中的“transaction-type”元素配置。JTA事务只能运行在J2EE的环境中，即EJB容器中和Web容器中；而在J2SE环境中只能使用RESOURCE_LOCAL管理事务。</p>
<p>2. 注意OneToMany,ManyToOne,ManyToMany三种关系时的参数配置.</p>
<p>3. Merge也有Persist的功能，数据库中有就merge，没有添加。</p>
<p>4. 注意Transaction的使用，不要一个方法中有几个Transaction。</p>
<p>5. 正确使用Eager和Lazy能显著提交效率。</p>
<p>6. 使用persist，只需注意操作的对象要么是new，要么是受管的，否则肯定出问题。</p>
<p>7. 使用merge，基本上无论如何都不会抛异常，但后续的操作必须针对该方法返回的新受管对象进行操作，否则肯定出问题。</p>
</blockquote>
<h3>四、参考资料</h3>
<blockquote><p>1. http://www.oracle.com/technology/products/ias/toplink/jpa/index.html</p>
<p>2. http://baike.baidu.com/view/1036852.htm?fr=ala0</p>
<p>3. http://java.sun.com/javaee/technologies/persistence.jsp</p>
<p>4. http://pz0513.blog.51cto.com/443986/113098</p></blockquote>
<p><span style="color: #800000;">==本文谢绝转载，谢谢==</span></p>
]]></content:encoded>
			<wfw:commentRss>http://www.quanlei.com/2009/11/0948-week-subject-jpa/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>JTable Print</title>
		<link>http://www.quanlei.com/2009/11/jtable_print/</link>
		<comments>http://www.quanlei.com/2009/11/jtable_print/#comments</comments>
		<pubDate>Tue, 17 Nov 2009 08:54:30 +0000</pubDate>
		<dc:creator>小权</dc:creator>
				<category><![CDATA[技术]]></category>
		<category><![CDATA[编程相关]]></category>
		<category><![CDATA[JasperReport]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[JTable]]></category>
		<category><![CDATA[打印]]></category>
		<category><![CDATA[表格]]></category>

		<guid isPermaLink="false">http://www.quanlei.com/?p=834</guid>
		<description><![CDATA[这几天在做关于JTable的打印工作，项目中客户需要直接将JTable打印出来，之前这方面工作做的比较少，经过这几天的研究，稍微有些积累，现在分享一下。 JTable打印目前用的比较多的还是JasperReport来实现的，JasperReport开源免费，但是不是特别好用，这也是为什么JasperReport免费用，但是培训是收费的。 不过常用的一些JTable的打印实现起来也还好了，只是复杂的稍微有些麻烦，可以看看我之前介绍的一篇入门文章：JasperReport 个人使用的一些经验 这里主要分享的是通过Swing 打印的积累，JasperReport常用的简单的打印没问题，但是遇上比较复杂的表单，比如合成表头等，就稍微有点麻烦，当然也有可能是自己没有找到JasperReport的处理方法，要是有朋友知道欢迎分享下。 通过Swing来绘制，应该是无奈的一步，不过通过这无奈的一步，和同事的帮助下，却学习到了不少这方面的知识，尤其是Swing绘制方面的。 下面的代码是我抽出来的一个比较通用的，基于TableModel的表格打印，普通表头，不带合成表头的，如果Table Model不一样，那么自己就需要改改了。 import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.print.PageFormat; import java.awt.print.Printable; import java.awt.print.PrinterException; import java.awt.print.PrinterJob; import java.math.BigDecimal; import java.text.NumberFormat; import javax.swing.JTable; import javax.swing.table.TableModel; /** * * @author xiaoquan */ public class SwingCommonPrinitTools implements Printable { private TableModel model = null; private String info; private int totalRow = [...]]]></description>
			<content:encoded><![CDATA[<p><span style="color: #000000;"><span style="color: #800000;"><span style="font-size: xx-large;">这</span></span>几天在做关于JTable的打印工作，项目中客户需要直接将JTable打印出来，之前这方面工作做的比较少，经过这几天的研究，稍微有些积累，现在分享一下。</span></p>
<p><span style="color: #000000;">JTable打印目前用的比较多的还是JasperReport来实现的，JasperReport开源免费，但是不是特别好用，这也是为什么JasperReport免费用，但是培训是收费的。</span></p>
<p><span style="color: #000000;">不过常用的一些JTable的打印实现起来也还好了，只是复杂的稍微有些麻烦，可以看看我之前介绍的一篇入门文章：<a href="http://disney2002.javaeye.com/blog/429385" target="_blank">JasperReport 个人使用的一些经验</a></span></p>
<p><span style="color: #000000;">这里主要分享的是通过Swing 打印的积累，JasperReport常用的简单的打印没问题，但是遇上比较复杂的表单，比如合成表头等，就稍微有点麻烦，当然也有可能是自己没有找到JasperReport的处理方法，要是有朋友知道欢迎分享下。</span></p>
<p><span style="color: #000000;">通过Swing来绘制，应该是无奈的一步，不过通过这无奈的一步，和同事的帮助下，却学习到了不少这方面的知识，尤其是Swing绘制方面的。</span></p>
<p><span style="color: #000000;">下面的代码是我抽出来的一个比较通用的，基于TableModel的表格打印，</span><span style="color: #000000;">普通表头，不带合成表头的，</span><span style="color: #000000;">如果Table Model不一样，那么自己就需要改改了。</span></p>
<pre class="brush: java;">
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.math.BigDecimal;
import java.text.NumberFormat;
import javax.swing.JTable;
import javax.swing.table.TableModel;

/**
 *
 * @author xiaoquan
 */
public class SwingCommonPrinitTools implements Printable {

    private TableModel model = null;
    private String info;
    private int totalRow = 0;
    private static final int LEFT = 0;
    private static final int RIGHT = 1;
    private static final int CENTER = 2;
    private static final int AUTO = 3;

    public void printTable(TableModel model,
            String info) {
        this.model = model;
        this.info = info;
        totalRow = model.getRowCount();
        PrinterJob printJob = PrinterJob.getPrinterJob();
        printJob.setPrintable(this);
        if (printJob.printDialog()) {
            try {
                printJob.print();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }
    private static final double paper_offset_x = 20;
    private static final double paper_offset_y = 20;
    private static final double title_time_margin = 10;
    private static final double time_body_margin = 2;
    private static final double cell_padding_y = 3;
    private static final double cell_padding_x = 2;
    private static final double body_btm_margin = 20;
    private static final double body_cell_height = 20;
    private static final Font title_font = new Font(&quot;黑体&quot;, Font.PLAIN, 18);
    private static final Font time_font = new Font(&quot;Dialog&quot;, Font.PLAIN, 10);
    private static final Font body_font = new Font(&quot;Dialog&quot;, Font.PLAIN, 10);

    @Override
    public int print(Graphics g, PageFormat pf, int pageIndex) throws
            PrinterException {
        //纸张宽
        double pageWidth = pf.getImageableWidth();
        //纸张高
        double pageHeight = pf.getImageableHeight();
        //打印的内容起始X
        double pageStartX = pf.getImageableX();
        //打印的内容起始Y
        double pageStartY = pf.getImageableY();

        //表头高
        double tableHeadH = 0;
        //Cell高
        double cellH = 0;

        //计算表头高度和单元格高度
        g.setFont(body_font);
        FontMetrics cellFm = g.getFontMetrics();
        cellH = cellFm.getHeight() + cell_padding_y * 2 + 1;
        tableHeadH = cellH * 2;

        //计算Title以及其位置
        String title = info;
        g.setFont(title_font);
        FontMetrics titleFm = g.getFontMetrics();
        int titleW = titleFm.stringWidth(title);

        //表底和表头文字属性
        g.setFont(time_font);
        FontMetrics btmFm = g.getFontMetrics();
        FontMetrics timeFm = g.getFontMetrics();

        //表格以上的Margin
        double tableTopMargin = paper_offset_y + titleFm.getHeight() +
                title_time_margin + timeFm.getHeight() + time_body_margin;

        //表格每列的最大宽度
        double[] cellColMaxWidths = caculateTableCellWidth(model, cellFm);

        //当前Page的数据容量高度-不包括表头和表尾
        double currentPageDataCapacityHeight = pageHeight - tableTopMargin -
                tableHeadH - btmFm.getHeight() - body_btm_margin - 1;

        //当前Page的数据容量
        int currentPageBodyCapacityRows = (int) (currentPageDataCapacityHeight /
                cellH);

        //Y方向的分页数量
        int pagesY = 0;
        if (model.getRowCount() % currentPageBodyCapacityRows == 0) {
            pagesY = (int) (model.getRowCount() /
                    currentPageBodyCapacityRows);
        } else {
            pagesY = (int) (model.getRowCount() /
                    currentPageBodyCapacityRows) +
                    1;
        }

        //当前页数大于总页数时不打印
        if (pageIndex + 1 &gt; pagesY) {
            return NO_SUCH_PAGE;
        }

        //绘制Title
        g.setFont(title_font);
        g.drawString(title, (int) (pageStartX +
                (pageWidth - titleW) / 2), (int) (pageStartY +
                paper_offset_y +
                titleFm.getAscent()));

        //绘制区域移动到新的(0,0)点
        g.translate((int) (paper_offset_x + pageStartX), (int) (tableTopMargin +
                pageStartY));
        int currentX = 0, currentY = 0;

        //绘制第一张表

        //绘制表头
        g.setFont(time_font);
        String time = &quot;表头: &quot; + info;
        g.drawString(time, currentX, currentY);
        currentY += 5;
        //绘制单一表头
        for (int i = 0; i &lt; model.getColumnCount(); i++) {
            double width = cellColMaxWidths[i];
            double height = tableHeadH;
            String name = model.getColumnName(i);
            drawCell(g, name, currentX, currentY, (int) width,
                    (int) height, CENTER);
            currentX += width;
        }

        //绘制数据
        currentX = 0;
        currentY = (int) tableHeadH;
        //当前Page的数据容量
        int rightCellX = 0;
        int yIndex = pageIndex;
        int startRow = currentPageBodyCapacityRows * yIndex;
        int endRow = (currentPageBodyCapacityRows * (yIndex + 1)) &gt;
                totalRow
                ? totalRow
                : (currentPageBodyCapacityRows * (yIndex + 1));
        for (int row = startRow; row &lt; endRow; row++) {
            //绘制单项表头下面的数据
            for (int i = 0; i &lt; model.getColumnCount(); i++) {
                double width = cellColMaxWidths[i];
                double height = body_cell_height;
                Object value = model.getValueAt(row, i);
                drawCell(g, value, currentX, currentY, (int) width,
                        (int) height, AUTO);
                currentX += width;
                rightCellX = currentX;
            }
            currentX = 0;
            currentY += cellH;
        }

        //绘制闭合线，下面和右侧两条
        g.drawLine(currentX, currentY, rightCellX, currentY);
        g.drawLine(rightCellX, 5, rightCellX, currentY);

        drawBottomInfo(pageIndex, pagesY, currentY, g, (int) pageWidth);
        return PAGE_EXISTS;
    }

    private void drawBottomInfo(int pageIndex, int pagesY,
            int currentY, Graphics g, int pageWidth) {
        if (pageIndex + 1 == pagesY) {
            //绘制底部信息
            int btmX = 0;
            int btmY = currentY + 20;
            g.drawString(&quot;负责人:&quot;, btmX, btmY);
            g.drawString(&quot;制表:&quot;, pageWidth / 3, btmY);
            FontMetrics fm = g.getFontMetrics();
            int dataWidth = fm.stringWidth(&quot;日期: 2009/10/26&quot;);
            g.drawString(&quot;日期:&quot;, pageWidth - dataWidth, btmY);
        }
    }

    /**
     * 计算最大列宽
     * @param cellFm
     * @return
     */
    private double[] caculateTableCellWidth(
            TableModel model,
            FontMetrics cellFm) {
        //表格每列的最大宽度
        double[] cellColMaxWidths = new double[model.getColumnCount()];

        //计算表头每列最大宽度
        double[] headerColMaxWidths = new double[model.getColumnCount()];

        for (int i = 0; i &lt; model.getColumnCount(); i++) {
            String name = model.getColumnName(i);
            headerColMaxWidths[i] = cellFm.stringWidth(name) + cell_padding_x *
                    2 + 1;
        }
        //没有数据时，表头每列的最大宽度就是表格每列的最大宽度
        cellColMaxWidths = headerColMaxWidths;

        //算数据每列的最大宽度和表头每列最大宽度对比
        for (int j = 0; j &lt; model.getRowCount(); j++) {
            for (int i = 0; i &lt; model.getColumnCount(); i++) {
                //做些数据类型的判断
                Object value = model.getValueAt(j, i);
                if (value instanceof BigDecimal) {
                    value = ((BigDecimal) value).doubleValue();
                }
                String text = &quot;&quot;;
                if (value != null) {
                    text = value.toString();
                }
                double temp = cellFm.stringWidth(text) + cell_padding_x * 2 + 1;
                if (cellColMaxWidths[i] &lt; temp) {
                    cellColMaxWidths[i] = temp;
                }
            }
        }
        return cellColMaxWidths;
    }

    /**
     * 绘制单元格及里面的文字
     * @param g
     * @param value
     * @param x
     * @param y
     * @param width
     * @param height
     */
    private static void drawCell(Graphics g, Object value, int x, int y,
            int width,
            int height, int locate) {

        g.drawLine(x, y, x + width - 1, y);
        g.drawLine(x, y, x, y + height - 1);
        FontMetrics fm = g.getFontMetrics();
        if (value == null) {
            value = &quot;&quot;;
        }
        switch (locate) {
            case 0:
                //居左
                g.drawString(value.toString(), (int) (x + cell_padding_x), y +
                        (height - fm.getHeight()) / 2 + fm.getAscent());
            case 1:
                //居右
                g.drawString(value.toString(),
                        (int) (x +
                        (width - fm.stringWidth(value.toString()) + width -
                        fm.stringWidth(value.toString()) - cell_padding_x) /
                        2), y +
                        (height - fm.getHeight()) / 2 + fm.getAscent());
            case 2:
                //居中
                g.drawString(value.toString(), x + (width - fm.stringWidth(
                        value.toString())) / 2, y + (height -
                        fm.getHeight()) / 2 + fm.getAscent());
            case 3:
                //自动判断
                NumberFormat formatter = NumberFormat.getNumberInstance();
                formatter.setMinimumFractionDigits(2);
                formatter.setMaximumFractionDigits(2);
                //根据数据类型左对齐还是右对齐绘制还是居中对齐
                if (value instanceof BigDecimal) {
                    //居右
                    value = ((BigDecimal) value).doubleValue();
                    value = formatter.format(value);
                    g.drawString(value.toString(),
                            (int) (x +
                            (width - fm.stringWidth(value.toString()) + width -
                            fm.stringWidth(value.toString()) - cell_padding_x) /
                            2), y +
                            (height - fm.getHeight()) / 2 + fm.getAscent());
                } else if (value instanceof Integer || value instanceof Long ||
                        value instanceof Double) {
                    //居右
                    g.drawString(value.toString(),
                            (int) (x +
                            (width - fm.stringWidth(value.toString()) + width -
                            fm.stringWidth(value.toString()) - cell_padding_x) /
                            2), y +
                            (height - fm.getHeight()) / 2 + fm.getAscent());
                } else {
                    //居中
                    g.drawString(value.toString(), x + (width - fm.stringWidth(
                            value.toString())) / 2, y + (height -
                            fm.getHeight()) / 2 + fm.getAscent());
                }
        }
    }

    public static void main(String[] args) {
        new SwingCommonPrinitTools().printTable(testData(), &quot;测试&quot;);
    }

    private static TableModel testData() {
        final Object rows[][] = {
            {&quot;one&quot;, &quot;ichi - \u4E00&quot;, &quot;Test1&quot;, &quot;Test2&quot;, &quot;Test3&quot;},
            {&quot;two&quot;, &quot;ni - \u4E8C&quot;, &quot;Test1&quot;, &quot;Test2&quot;, &quot;Test3&quot;},
            {&quot;three&quot;, &quot;san - \u4E09&quot;, &quot;Test1&quot;, &quot;Test2&quot;, &quot;Test3&quot;},
            {&quot;four&quot;, &quot;shi - \u56DB&quot;, &quot;Test1&quot;, &quot;Test2&quot;, &quot;Test3&quot;},
            {&quot;five&quot;, &quot;go - \u4E94&quot;, &quot;Test1&quot;, &quot;Test2&quot;, &quot;Test3&quot;},
            {&quot;six&quot;, &quot;roku - \u516D&quot;, &quot;Test1&quot;, &quot;Test2&quot;, &quot;Test3&quot;},
            {&quot;seven&quot;, &quot;shichi - \u4E03&quot;, &quot;Test1&quot;, &quot;Test2&quot;, &quot;Test3&quot;},
            {&quot;eight&quot;, &quot;hachi - \u516B&quot;, &quot;Test1&quot;, &quot;Test2&quot;, &quot;Test3&quot;},
            {&quot;nine&quot;, &quot;kyu - \u4E5D&quot;, &quot;Test1&quot;, &quot;Test2&quot;, &quot;Test3&quot;},
            {&quot;ten&quot;, &quot;ju - \u5341&quot;, &quot;Test1&quot;, &quot;Test2&quot;, &quot;Test3&quot;},
            {&quot;one&quot;, &quot;ichi - \u4E00&quot;, &quot;Test1&quot;, &quot;Test2&quot;, &quot;Test3&quot;},
            {&quot;two&quot;, &quot;ni - \u4E8C&quot;, &quot;Test1&quot;, &quot;Test2&quot;, &quot;Test3&quot;},
            {&quot;three&quot;, &quot;san - \u4E09&quot;, &quot;Test1&quot;, &quot;Test2&quot;, &quot;Test3&quot;},
            {&quot;four&quot;, &quot;shi - \u56DB&quot;, &quot;Test1&quot;, &quot;Test2&quot;, &quot;Test3&quot;},
            {&quot;five&quot;, &quot;go - \u4E94&quot;, &quot;Test1&quot;, &quot;Test2&quot;, &quot;Test3&quot;},
            {&quot;six&quot;, &quot;roku - \u516D&quot;, &quot;Test1&quot;, &quot;Test2&quot;, &quot;Test3&quot;},
            {&quot;seven&quot;, &quot;shichi - \u4E03&quot;, &quot;Test1&quot;, &quot;Test2&quot;, &quot;Test3&quot;},
            {&quot;eight&quot;, &quot;hachi - \u516B&quot;, &quot;Test1&quot;, &quot;Test2&quot;, &quot;Test3&quot;},
            {&quot;nine&quot;, &quot;kyu - \u4E5D&quot;, &quot;Test1&quot;, &quot;Test2&quot;, &quot;Test3&quot;},
            {&quot;ten&quot;, &quot;ju - \u5341&quot;, &quot;Test1&quot;, &quot;Test2&quot;, &quot;Test3&quot;},
            {&quot;one&quot;, &quot;ichi - \u4E00&quot;, &quot;Test1&quot;, &quot;Test2&quot;, &quot;Test3&quot;},
            {&quot;two&quot;, &quot;ni - \u4E8C&quot;, &quot;Test1&quot;, &quot;Test2&quot;, &quot;Test3&quot;},
            {&quot;three&quot;, &quot;san - \u4E09&quot;, &quot;Test1&quot;, &quot;Test2&quot;, &quot;Test3&quot;},
            {&quot;four&quot;, &quot;shi - \u56DB&quot;, &quot;Test1&quot;, &quot;Test2&quot;, &quot;Test3&quot;},
            {&quot;five&quot;, &quot;go - \u4E94&quot;, &quot;Test1&quot;, &quot;Test2&quot;, &quot;Test3&quot;},
            {&quot;six&quot;, &quot;roku - \u516D&quot;, &quot;Test1&quot;, &quot;Test2&quot;, &quot;Test3&quot;},
            {&quot;seven&quot;, &quot;shichi - \u4E03&quot;, &quot;Test1&quot;, &quot;Test2&quot;, &quot;Test3&quot;},
            {&quot;eight&quot;, &quot;hachi - \u516B&quot;, &quot;Test1&quot;, &quot;Test2&quot;, &quot;Test3&quot;},
            {&quot;nine&quot;, &quot;kyu - \u4E5D&quot;, &quot;Test1&quot;, &quot;Test2&quot;, &quot;Test3&quot;},
            {&quot;ten&quot;, &quot;ju - \u5341&quot;, &quot;Test1&quot;, &quot;Test2&quot;, &quot;Test3&quot;},
            {&quot;one&quot;, &quot;ichi - \u4E00&quot;, &quot;Test1&quot;, &quot;Test2&quot;, &quot;Test3&quot;},
            {&quot;two&quot;, &quot;ni - \u4E8C&quot;, &quot;Test1&quot;, &quot;Test2&quot;, &quot;Test3&quot;},
            {&quot;three&quot;, &quot;san - \u4E09&quot;, &quot;Test1&quot;, &quot;Test2&quot;, &quot;Test3&quot;},
            {&quot;four&quot;, &quot;shi - \u56DB&quot;, &quot;Test1&quot;, &quot;Test2&quot;, &quot;Test3&quot;},
            {&quot;five&quot;, &quot;go - \u4E94&quot;, &quot;Test1&quot;, &quot;Test2&quot;, &quot;Test3&quot;},
            {&quot;six&quot;, &quot;roku - \u516D&quot;, &quot;Test1&quot;, &quot;Test2&quot;, &quot;Test3&quot;},
            {&quot;seven&quot;, &quot;shichi - \u4E03&quot;, &quot;Test1&quot;, &quot;Test2&quot;, &quot;Test3&quot;},
            {&quot;eight&quot;, &quot;hachi - \u516B&quot;, &quot;Test1&quot;, &quot;Tes12121t2&quot;, &quot;Test3&quot;},
            {&quot;nine&quot;, &quot;kyu - \u4E5D&quot;, &quot;Test1&quot;, &quot;Test2&quot;, &quot;Test3&quot;},
            {&quot;ten&quot;, &quot;ju - \u5341&quot;, &quot;Test1&quot;, &quot;Test2&quot;, &quot;Test3&quot;},
            {&quot;one&quot;, &quot;ichi - \u4E00&quot;, &quot;Test1&quot;, &quot;Test2&quot;, &quot;Test3&quot;},
            {&quot;two&quot;, &quot;ni - \u4E8C&quot;, &quot;Test1&quot;, &quot;Test2&quot;, &quot;Test3&quot;},
            {&quot;three&quot;, &quot;san - \u4E09&quot;, &quot;Test1&quot;, &quot;Test2&quot;, &quot;Test3&quot;},
            {&quot;four&quot;, &quot;shi - \u56DB&quot;, 12, &quot;Test2&quot;, &quot;Test3&quot;},
            {&quot;five&quot;, &quot;go - \u4E94&quot;, 121212, &quot;Test2&quot;, &quot;Test3&quot;},
            {&quot;six&quot;, &quot;roku - \u516D&quot;, 1212121212, &quot;Test2&quot;, &quot;Test3&quot;},
            {&quot;seven&quot;, &quot;shichi - \u4E03&quot;, 12.01, &quot;Test2&quot;, &quot;Test3&quot;},
            {&quot;eight&quot;, &quot;hachi - \u516B&quot;, 135.12, &quot;Test2&quot;, &quot;Test3&quot;},
            {&quot;nine&quot;, &quot;kyu - \u4E5D&quot;, 93828.34, &quot;Test2&quot;, &quot;Test3&quot;},
            {&quot;ten&quot;, &quot;ju - \u5341&quot;, &quot;Test1&quot;, &quot;Test2&quot;, &quot;Test3&quot;},
            {&quot;one&quot;, &quot;ichi - \u4E00&quot;, &quot;Test1&quot;, &quot;Test2&quot;, &quot;Test3&quot;},
            {&quot;two&quot;, &quot;ni - \u4E8C&quot;, &quot;Test1&quot;, &quot;Test2&quot;, &quot;Test3&quot;},
            {&quot;three&quot;, &quot;san - \u4E09&quot;, &quot;Test1&quot;, &quot;Test2&quot;, &quot;Test3&quot;},
            {&quot;four&quot;, &quot;shi - \u56DB&quot;, &quot;Test1&quot;, &quot;Test2&quot;, &quot;Test3&quot;},
            {&quot;five&quot;, &quot;go - \u4E94&quot;, &quot;Test1&quot;, &quot;Test2&quot;, &quot;Test3&quot;},
            {&quot;six&quot;, &quot;roku - \u516D&quot;, &quot;Test1&quot;, &quot;Test2&quot;, &quot;Test3&quot;},
            {&quot;seven&quot;, &quot;shichi - \u4E03&quot;, &quot;Test1&quot;, &quot;Test2&quot;, &quot;Test3&quot;},
            {&quot;eight&quot;, &quot;hachi - \u516B&quot;, &quot;Test1&quot;, &quot;Test2&quot;, &quot;T1212121212est3&quot;},
            {&quot;nine&quot;, &quot;kyu - \u4E5D&quot;, &quot;Test1&quot;, &quot;Test2&quot;, &quot;Test3&quot;},
            {&quot;ten&quot;, &quot;ju - \u5341&quot;, &quot;Test1&quot;, &quot;Test2&quot;, &quot;Test3&quot;},};
        final Object headers[] = {&quot;English&quot;, &quot;Japanese&quot;, &quot;Column1&quot;, &quot;Column2&quot;,
            &quot;Column3&quot;};
        JTable table = new JTable(rows, headers);
        return table.getModel();
    }
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.quanlei.com/2009/11/jtable_print/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Install Java Plugin To Linux FireFox</title>
		<link>http://www.quanlei.com/2009/11/install-java-plugin-to-linux-firefox/</link>
		<comments>http://www.quanlei.com/2009/11/install-java-plugin-to-linux-firefox/#comments</comments>
		<pubDate>Fri, 13 Nov 2009 03:22:50 +0000</pubDate>
		<dc:creator>小权</dc:creator>
				<category><![CDATA[Linux服务器相关]]></category>
		<category><![CDATA[技术]]></category>
		<category><![CDATA[Firefox]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[ubunutu]]></category>

		<guid isPermaLink="false">http://www.quanlei.com/?p=825</guid>
		<description><![CDATA[前提是保证你的Linux已经安装了相应的Java软件，如果没有安装Java, 先装安装Java，配置Java环境, 假如安装到了/usr/java/jre1.6.0_17/ 找到你的FireFox安装的目录，假如安装到了 /usr/firefox cd /usr/firfox 如果有plugins目录那就继续往下看，如果没有，mkdir plugins ln -s /usr/java/jre1.6.0_17/plugin/i386/ns7/libjavaplugin_oji.so OK，至此大功告成，测试一下，打开 http://www.java.com/zh_CN/download/installed.jsp 看看即可 ubuntu下安装这个其实很方便，firefox会自动检测并让你安装，java plugin， 但是在有些Linux环境下就需要手动了。]]></description>
			<content:encoded><![CDATA[<p><span style="color: #000000;"><span style="color: #800000;"><span style="font-size: xx-large;">前</span></span>提是保证你的Linux已经安装了相应的Java软件，如果没有安装Java, 先装安装Java，配置Java环境, 假如安装到了/usr/java/jre1.6.0_17/<br />
</span></p>
<p><span style="color: #000000;">找到你的FireFox安装的目录，假如安装到了 /usr/firefox</span></p>
<p><span style="color: #800000;"><em>cd /usr/firfox</em></span></p>
<p><span style="color: #000000;">如果有plugins目录那就继续往下看，如果没有，<span style="color: #800000;"><em>mkdir plugins</em></span></span></p>
<p><span style="color: #800000;"><em>ln -s /usr/java/jre1.6.0_17/plugin/i386/ns7/libjavaplugin_oji.so</em></span></p>
<p><span style="color: #000000;">OK，至此大功告成，测试一下，打开 <a href="http://www.java.com/zh_CN/download/installed.jsp">http://www.java.com/zh_CN/download/installed.jsp</a> 看看即可</span></p>
<p><span style="color: #000000;">ubuntu下安装这个其实很方便，firefox会自动检测并让你安装，java plugin， 但是在有些Linux环境下就需要手动了。<br />
</span></p>
]]></content:encoded>
			<wfw:commentRss>http://www.quanlei.com/2009/11/install-java-plugin-to-linux-firefox/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
