13.07.2015 Views

Java™ Application Development on Linux - Dator

Java™ Application Development on Linux - Dator

Java™ Application Development on Linux - Dator

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

364Chapter 16Getting in the Swing of Things: Designing a GUI for BudgetProreturn an object which has a toString(), we’re fine. Both User and SAM<strong>on</strong>eydo have such a method, so they fit fine here.The more complex answer has to do with why JTable calls thetoString() method at all. The JTable uses, behind the scenes, a complextable cell display mechanism, called a table cell renderer. A renderer is an objectthat displays data in a certain way. Each table cell renderer returns a GUIcomp<strong>on</strong>ent, and if you d<strong>on</strong>’t want to use the default renderer, you can defineyour own table cell renderer for your table. This allows you to display almostanything you can imagine inside a table’s cell. The renderer acts as a templatefor those cells and will be called up<strong>on</strong> with the result of the getValueAt(),al<strong>on</strong>g with a few more parameters, so that it can build and display theresulting cell.Let’s revisit our simple explanati<strong>on</strong> above, in light of the c<strong>on</strong>cept of arenderer. The default cell renderer for a JTable uses just a JLabel. Whencalled up<strong>on</strong>, the default cell renderer is given the object returned bygetValueAt() and the renderer fills its JLabel by calling its setText()method, passing in the result of toString() <strong>on</strong> the given object. That’s howtoString() got called <strong>on</strong> all our results. You can explicitly set a differentrenderer using the setDefaultRenderer() method <strong>on</strong> JTable.In the Javadoc for Swing table objects we find this interface:public Comp<strong>on</strong>entgetTableCellRendererComp<strong>on</strong>ent(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, itneeds to implement this method. The method will be called with the valuereturned by getValueAt(), but the row and column (and table) will berepeated here in case your renderer cares. For example, having the row andcolumn would allow you to create a table with the third column of the tablein 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 theComp<strong>on</strong>ent that you would return.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!