A way to achieve that, it’s creating a TableModel class which extends from a AbstractTableModel. Here is an example:
Code:
import javax.swing.table.AbstractTableModel;
public class MyTableModel extends AbstractTableModel{
String[] columnNames = {"First Name",
"Last Name",
"Sport",
"# of Years"};
Object[][] data = {
{"Mary", "Campione",
"Snowboarding", new Integer(5)},
{"Alison", "Huml",
"Rowing", new Integer(3)},
{"Kathy", "Walrath",
"Knitting", new Integer(2)}};
public MyTableModel(){
}
public int getColumnCount() {
return columnNames.length;
}
public int getRowCount() {
return data.length;
}
public String getColumnName(int col) {
return columnNames[col];
}
public Object getValueAt(int row, int col) {
return data[row][col];
}
public boolean isCellEditable(int row, int col) {
return false;
}
}
If you want, you can test it, using the following code:
Code:
import java.awt.*;
import javax.swing.*;
public class JTableSample extends JFrame{
public JTableSample() {
JTable table = new JTable(new MyTableModel());
table.setPreferredScrollableViewportSize(new Dimension(500, 70));
//Create the scroll pane and add the table to it.
JScrollPane scrollPane = new JScrollPane(table);
//Add the scroll pane to this panel.
this.getContentPane().add(scrollPane);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setSize(500,300);
}
public static void main(String[] args) {
JTableSample t = new JTableSample();
t.setVisible(true);
}
}
For more information, I recommend you to take a look in the following links.
http://java.sun.com/docs/books/tutor...able.html#data
http://java.sun.com/j2se/1.4.2/docs/...ableModel.html
Regards!!
Bookmarks