Search code examples
javatablecellrenderer

How does this method nesting work? [TableRowRenderingTip.java]


When looking for something on the java documentation I realized there's some kind of nesting I've never seen before, so If you could explain what is it or how is it called I would be very grateful.

It's my first question in StackOverflow so I'm sorry if I broke any rule.

Code:

private JComponent createData(DefaultTableModel model)
{
    JTable table = new JTable( model )
    {    //What are these brackets for? I know it contains a method but I've never seen a method "nested" with a variable initialization.
        public Component prepareRenderer(TableCellRenderer renderer, int row, int column)
        {
            Component c = super.prepareRenderer(renderer, row, column);

            //  Color row based on a cell value

            if (!isRowSelected(row))
            {
                c.setBackground(getBackground());
                int modelRow = convertRowIndexToModel(row);
                String type = (String)getModel().getValueAt(modelRow, 0);
                if ("Buy".equals(type)) c.setBackground(Color.GREEN);
                if ("Sell".equals(type)) c.setBackground(Color.YELLOW);
            }

            return c;
        }
    };

Don't really know how to properly use the question editor.

Thanks in advance!

Here's the full source code.


Solution

  • What you have found is called as anonymous class. In the example it extends JTable class, but because it do not want to use it multiple times it does not give a name to the new class (hence anonymous), instead it creates an instance of it instantly, and stores it in the table variable. In the new class it overrides the prepareRenderer method of the original JTable.

    Here you can read more about anonymous classes: https://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html