读书人

Swing中的TableCellRenderer与TableCe

发布时间: 2013-10-15 16:47:37 作者: rapoo

Swing中的TableCellRenderer与TableCellEditor的作用

受够了,Swing中的CellRenderer与CellEditor的作用,一直困扰着我,到了必须要熟悉的时候了!

下面三句话是读官方文档的最大收获,也是理解这两个概念的核心

The Renderer used to draw the data cells of the column using the specific compenent such as the JLabel, JCheckbox, and so on. 即界面在展示的时候调用的类

The Editor used to take over the cell, controlling the cell's editing behavior when the user start to edit the cell's data. 即当用户在点击单元格的时候,调用的类

BTW, the same cell, the Render and Editor could use the different compenet to react the behavior.

关于上面这几点,首先阐述上面结论的出处仅将摘出重要的点,然后最后会有一个自定义的JCheckbox作为具体的实例,来理解这三点的应用和用处!


官方文档:

http://docs.oracle.com/javase/tutorial/uaiswing/components/table.html#editrender

Before you go on, you need to understand how tables draw their cells. You might expect each cell in a table to be a component. However, for performance reasons, Swing tables are implemented differently.

Instead, a single cell renderer is generally used to draw all of the cells that contain the same type of data. You can think of therenderer as a configurable ink stamp that the table uses to stamp appropriately formatted data onto each cell. When the user starts to edit a cell's data, a cell editor takes over the cell, controlling the cell's editing behavior.

For example, each cell in the # of Years column in TableDemo contains Number data — specifically, an Integer object. By default, the cell renderer for a Number-containing column uses a single JLabel instance to draw the appropriate numbers, right-aligned, on the column's cells. If the user begins editing one of the cells, the default cell editor uses a right-aligned JTextField to control the cell editing.

To choose the renderer that displays the cells in a column, a table first determines whether you specified a renderer for that particular column. If you did not, then the table invokes the table model's getColumnClass method, which gets the data type of the column's cells. Next, the table compares the column's data type with a list of data types for which cell renderers are registered. This list is initialized by the table, but you can add to it or change it. Currently, tables put the following types of data in the list:

读书人网 >编程

热点推荐