这种方法嵌套是如何工作的? [TableRowRenderingTip.java]
How does this method nesting work? [TableRowRenderingTip.java]
在 java 文档中查找内容时,我意识到存在某种我以前从未见过的嵌套,因此如果您能解释它是什么或它是如何命名的,我将不胜感激。
这是我在 Whosebug 中的第一个问题,如果我违反了任何规则,我深表歉意。
代码:
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;
}
};
不知道如何正确使用问题编辑器。
提前致谢!
Here's 完整的源代码。
您找到的内容称为匿名 class。在示例中,它扩展了 JTable
class,但是因为它不想多次使用它,所以它没有为新的 class 命名(因此是匿名的),而是创建了一个实例,并将其存储在 table
变量中。
在新的 class 中,它覆盖了原始 JTable
的 prepareRenderer
方法。
在这里您可以阅读更多关于匿名 classes 的信息:
https://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html
在 java 文档中查找内容时,我意识到存在某种我以前从未见过的嵌套,因此如果您能解释它是什么或它是如何命名的,我将不胜感激。
这是我在 Whosebug 中的第一个问题,如果我违反了任何规则,我深表歉意。
代码:
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;
}
};
不知道如何正确使用问题编辑器。
提前致谢!
Here's 完整的源代码。
您找到的内容称为匿名 class。在示例中,它扩展了 JTable
class,但是因为它不想多次使用它,所以它没有为新的 class 命名(因此是匿名的),而是创建了一个实例,并将其存储在 table
变量中。
在新的 class 中,它覆盖了原始 JTable
的 prepareRenderer
方法。
在这里您可以阅读更多关于匿名 classes 的信息: https://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html