Java Reference
In-Depth Information
return an object which has a toString() , we're fine. Both User and SAMoney
do have such a method, so they fit fine here.
The more complex answer has to do with why JTable calls the
toString() method at all. The JTable uses, behind the scenes, a complex
table cell display mechanism, called a table cell renderer . A renderer is an object
that displays data in a certain way. Each table cell renderer returns a GUI
component, and if you don't want to use the default renderer, you can define
your own table cell renderer for your table. This allows you to display almost
anything you can imagine inside a table's cell. The renderer acts as a template
for those cells and will be called upon with the result of the getValueAt() ,
along with a few more parameters, so that it can build and display the
resulting cell.
Let's revisit our simple explanation above, in light of the concept of a
renderer. The default cell renderer for a JTable uses just a JLabel . When
called upon, the default cell renderer is given the object returned by
getValueAt() and the renderer fills its JLabel by calling its setText()
method, passing in the result of toString() on the given object. That's how
toString() got called on all our results. You can explicitly set a different
renderer using the setDefaultRenderer() method on JTable .
In the Javadoc for Swing table objects we find this interface:
public Component
getTableCellRendererComponent(JTable table,
Object value,
boolean isSelected,
boolean hasFocus,
int row,
int column)
This tells us that if we want to write a class which can act as a renderer, it
needs to implement this method. The method will be called with the value
returned by getValueAt() , but the row and column (and table ) will be
repeated here in case your renderer cares. For example, having the row and
column would allow you to create a table with the third column of the table
in green—your method could check the column number, and if it is 2
(columns are numbered 0, 1, 2, . . . ) set the background color to green for the
Component that you would return.
Search WWH ::




Custom Search