How to create specific class constructor
I have a very simple Java JTable question. I am creating this class to make things easier in the rest of my application. I receive an error when running it. I know what the errors mean, but have no idea what else to try.
You'll see in the code what I am trying to accomplish:
My Class:
import javax.swing.*;
public class CPTable extends JScrollPane
{
private JTable table;
CPTable(Object [] headers, Object [][] data)
{
table = new JTable(data, header开发者_运维技巧s);
this = new JScrollPane(table);//The line I can't figure out.
}
}
My errors: (an obvious one)
cannot assign a value to final variable this
this = new JScrollPane(table);
and
incompatible types
found : javax.swing.JScrollPane
required: CPTable
Try this:
private CPTable(JTable table) {
super(table);
this.table = table;
}
public CPTable(Object[] headers, Object[][] data) {
this(new JTable(data, headers));
}
You cannot reassign this
, but you can cause the correct superclass constructor to be called by using super
(which must be the first statement in your constructor).
The this
statement is called "constructor delegation"---it chains through to the other constructor so that you can pass the table to the superclass as well as assign it to your table
field.
精彩评论