Getting a JTable with a custom table model to show up in JScrollPane
I am attempting to create my own custom TableModel for my JTable (because I would like to incorporate a row of JCheckBox's into my table.) I have the JTable in a JScrollPane as well. Before I attempted to incorporate the JCheckBox and custom AbstractTableModel, the JTable would show up fine if I used the default (Object[][], Object[]) constructor. I read in the JTable tutorial on Sun that those constructors use a default of treating all data as Strings.
I then created my custom AbstractTableModel and went from this:
JTable table = new JTable(dataArray, col);
To This:
JTable table = new JTable();
I am assuming that this would call attempt to create the 开发者_Python百科JTable with the custom-made class that extends AbstractTableModel, but now nothing shows up in the JScrollPane.
I am using this incorrectly? I virtually copied the code from the Sun tutorial and only changed the names of the datafiles involved. I also placed this method in the same class. Is there a different way to make sure that your table is created with your custom Table Model? Any insight would appreciated.
JTable
has several constructors that take a TableModel
as a parameter. Is that what you're looking for? From the code snippet you supplied, it seems like you're calling the default constructor and expecting it to use your custom table model somehow. (Maybe there's some code missing that does this?). If you use the default constructor, JTable
will internally create a DefaultTableModel
instance and use that.
Edit: Comments don't take code very well, so adding here: To get the table to use your model, you would do something like this:
MyTableModel model = new MyTableModel();
// ...initialise model if required
JTable table = new JTable(model);
As you observed, Ash is right on about passing your data model in the JTable
constructor. If your model's getColumnClass()
returns Boolean.class
, you'll get a check box renderer by default. You might like this example that illustrates using a custom renderer and editor.
OK. After reviewing my code I realized that if I am leaving out any constructors, it will not find the link to your custom Table Model. So, if you created the class:
class MyTableModel extends AbstractTableModel {
//code here
}
You need to instantiate it in the JTable constructor like this:
JTable table = new JTable(new MyTableModel());
So you cannot just leave it blank and expect it to "find" the new AbstractTableModel class.
You need to extend AbstractTableModel
, and pass this as a parameter for the constructor of your JTable. (As Marc does). In addition to the required method, you need to define this method to show the actual checkboxes:
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
This tells you JTable how to render each cell. If you dont override this, it will just be showed as a string.
精彩评论