swing treetable 表格树

sun网站上有表格树的实现:

网址:http://java.sun.com/products/jfc/tsc/articles/treetable1/

---------------------------------------------------------------------------------------------------------------------------------------------------------------------

 
Article

Creating TreeTables in Swing

  
 

Creating TreeTablesin Swing
Just Use a JTreeto Render JTable Cells

Note: please also see part2 and part3 for further updates of TreeTable

By Philip Milne

A TreeTable is a combinationof a Tree and a Table -- a component capable of both expanding and contractingrows, as well as showing multiple columns of data. The Swing package doesnot contain a JTreeTable component, but it is fairly easy to create one byinstalling a JTree as a renderer for the cells in a JTable.

This article explains how to use this technique to create a TreeTable. Itconcludes with a example application, named TreeTableExample0, whichdisplays a working TreeTable browser that you can use to browse a local filesystem (see illustration).

In Swing, the JTree, JTable, JList, and JComboBox components use a singledelegate object called a cell renderer to draw their contents.  Acell renderer is a component whose paint() method is used to draweach item in a list, each node in a tree, or each cell in a table.  Acell renderer component can be viewed as a "rubber stamp": it'smoved into each cell location using setBounds(), and is then drawnwith the component's paint() method.

By using a component to render cells, you can achieve the effect of displayinga large number of components for the cost of creating just one.  Bydefault, the Swing components that employ cell renderers simply use a JLabel,which supports the drawing of simple combinations of text and an icon.To use any Swing component as a cell renderer, all you have to do is createa subclass that implements the appropriate cell renderer interface: TableCellRendererfor JTable, ListCellRenderer for JList, and so on.

Rendering in Swing

Here's an example of how you can extend a JCheckBox to act as a rendererin a JTable:

    public class CheckBoxRenderer extends JCheckBox          
                 implements TableCellRenderer          { 
        public Component getTableCellRendererComponent(JTable table, 
               Object value, boolean isSelected, 
               boolean hasFocus, int row, int column) { 
                       setSelected(((Boolean)value).booleanValue())); 
                       return this; 
                 } 
       }

How the example program works

The code snippet shown above -- part of a sample program presented infull later in this article -- shows how to use a JTree as a renderer insidea JTable. This is a slightly unusual case because it uses the JTree topaint a single node in each cell of the table rather than painting a completecopy of the tree in each of the cells.
 
We start in the usual way: expanding the JTree into a cell render by extendingit to implement the TableCellRenderer interface. To implement the requiredbehavior or a cell renderer, we must arrange for our renderer to paint justthe node of the tree that is visible in a particular cell. One simple way toachieve this is to override the setBounds() and paint() methods,as follows:


 public class TreeTableCellRenderer extends JTree 
             implements TableCellRenderer { 
    protected int visibleRow; 
    public void setBounds(int x, int y, int w, int h) { 
              super.setBounds(x, 0, w, table.getHeight());          
          } 
    public void paint(Graphics g) { 
              g.translate(0, -visibleRow * getRowHeight());          
              super.paint(g); 
          } 
    public Component getTableCellRendererComponent(JTable table,          
              object value, 
              boolean isSelected, 
              boolean hasFocus, 
              int row, int column) { 
                  visibleRow = row; 
                  return this; 
              } 
 } 

As each cell is painted, the JTable goes through the usual process ofgetting the renderer, setting its bounds, and asking it to paint. In thiscase, though, we record the row number of the cell being painted in aninstance variable named visibleRow.We also override setBounds(),so that the JTree remains the same height as the JTable, despite the JTable'sattempts to set its bounds to fit the dimensions of the cell being painted.

To complete this technique we override paint(),making use of the stored variable visibleRow,an operation that effectively moves the clipping rectangle over the appropriatepart of the tree. The result is that the JTree draws just one of its nodeseach time the table requests it to paint.

In addition to installing the JTree as a renderer for the cells in thefirst column, we install the JTree as the editor for these cells also.The effect of this strategy is the JTable then passes all mouse and keyboardevents to this "editor" -- thus allowing the tree to expand andcontract its nodes as a result of user input.

Example: A file-systembrowser

The example program presented with this article creates and implementsa browser for a file system. Each directory can be expanded and collapsed.Other columns in the table display important properties of files and directories,such as file sizes and dates.

Note: Correct Swing Version Required

Tocompile and run the example program provided with this article, youmust use Swing 1.1 Beta 2 or a compatible Swing release.

Here is the full list of classes used in the example program, along witha brief description of what each class does (you can download or view eachfile by clicking its link):

  • TreeTableModel.java:A new interface, extending the TreeModel interface, which describes thekind of data that can be drawn by a TreeTable.

  • AbstractTreeTableModel.java:A base class for TreeTableModels. This class handles the list of listeners.

  • TreeTableModelAdapter.java:A wrapper class that implements the TableModel interface, given bothTreeTableModel and a JTree.

  • AbstractCellEditor.java:A base class for CellEditors. This class handlers the list of listeners.

  • JTreeTable.java:A subclass of JTable, this class can render data from a TreeTableModel.

  • MergeSort.java:An implementation of merge sort.

  • FileSystemModel.java:A model of the local file system, implemented as a concrete subclassof AbstractTreeTableModel. This class implements the TreeTableModel interface.

  • TreeTableExample0.java:A demonstration program showing the TreeTable in action.

  • sources.zip:A zipped file containing of the above.
When you execute the TreeTableExample0 program, it displays a TreeTable showingthe files and directories in a file system, as shown in the diagram at thebeginning of this article. When you click on a branch element in the firstcolumn of the table, the item expands or collapses, just as it would in anyother tree.

Caveats

For clarity, we have kept the TreeTableExample0 program short. To be complete,a full-featured JTreeTable component would have to deal with a number ofother issues. Here are some features that are missing from this chapter'ssample program:
  • The TreeTable does not update itself in response to tree events.

  • The view on the file system never updates. If a directory is removedwhile one is viewing it, the display does not update itself accordingly.

  • The selected TreePaths, maintained in the TreeSelectionModel, maynot match what is visually selected.

  • When the selection is changed by user input to the JTree, the tableshould autoscroll to make sure the new lead selection index is visible.

copyright © Sun Microsystems, Inc 
 


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值