Listing 10.1 Simple Table (TJTable1.java)
// Demonstrates how to create a simple table with the
// specified number of rows and columns.
/*
*
*/
import javax.swing.*;
public class TJTable1 extends JApplet {
public void init() {
// 1. Create a table using the number of rows and
// columns and add it to the content pane.
JTable table = new JTable(4,5); // 4 rows & 5 columns
getContentPane().add(table);
}
}
Listing 10.2 Table Created Using Arrays of Data (TJTable2.java)
// Demonstrates how to create a simple table with the
// specified row data and column data.
/*
*
*/
import javax.swing.*;
import java.awt.*;
import java.util.*;
public class TJTable2 extends JApplet {
// Create an array of names to be displayed in the table
// header.
String[] columnNames = {"Name", "Size (Bytes)", "Date", "Directory"};
// Create an array of row data (each row is an array) to be
// displayed in the rows of the table.
Object[][] rowData = {
{"AUTOEXEC.BAT", "149", "09-11-98", new Boolean(false)},
{"REAL", "DIR", "12-11-97", new Boolean(true)},
{"WINDOWS", "DIR", "03-24-97", new Boolean(true)},
{"COMMAND.COM", "92879", "07-11-97", new Boolean(false)}};
public void init() {
// 1. Create a table by using the row and column data.
JTable table = new JTable(rowData, columnNames);
// 2. Add the table column header and the
// table to the content pane of the applet.
getContentPane().add(table.getTableHeader(), BorderLayout.NORTH);
getContentPane().add(table);
}
}
Listing 10.3 Custom Table Model (TTableModel.java)
// Demonstrates a custom table model.
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
public class TTableModel extends JFrame {
Container container;
JTable table;
JScrollPane scrollPane;
JLabel label;
JTextField textField;
public TTableModel() {
// 1. Assign a title to the frame and get
// the handle on the content pane.
super("TTableModel");
container = this.getContentPane();
// 2. Create a label and text field and add
// them to a panel.
label = new JLabel(
"Enter A Valid Directory Name and Press Return",
JLabel.CENTER);
textField = new JTextField();
textField.addActionListener(new TextFieldListener());
JPanel panel = new JPanel(new GridLayout(2,1));
panel.add(label);
panel.add(textField);
// 3. Get the root/system home. Use this home directory
// to create a file object that is used by the directory
// or file system model construct the table model. Also
// display the home directory in the text field.
String home = System.getProperty("user.home");
table = new JTable(new DirectoryModel(new File(home)));
table.createDefaultColumnsFromModel();
textField.setText(home);
// 4. Add the panel and table to the container.
container.add(BorderLayout.NORTH, panel);
container.add(new JScrollPane(table));
// 5. Frame settings.
// Add the window closing listener.
addWindowListener(new WindowEventHandler());
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
setBackground(Color.white);
setSize(350, 300); // Frame width=350, height=300
show(); // Display the frame
}
// 6. Window event handler.
class WindowEventHandler extends WindowAdapter {
public void windowClosing(WindowEvent evt) {
System.exit(0);
}
}
// 7. The main method.
public static void main(String[] args) {
TTableModel frame = new TTableModel();
}
// 8. Text field listener.
class TextFieldListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
// 9. Get the next directory name entered in
// the text field, prepare the model, and display
// the table by assigning the new data.
DirectoryModel model = new DirectoryModel(
new File(textField.getText()));
table.setModel(model);
}
}
}
// 10. The "Directory" or "FileSystem" model.
class DirectoryModel extends AbstractTableModel {
File directory;
String[] members;
int rowCount;
// 11. Model constructor.
public DirectoryModel(File dir) {
directory = dir; // Hold the directory
members = dir.list(); // Get the list of files
// and subdirectories
if (members != null)
// Table rows = No. of entities inside the directory
rowCount = members.length;
else {
// If the memeber list is null, row count should be zero.
rowCount = 0;
// This can happen if an invalid directory is entered
// in the text field.
System.out.println("Not a valid directory!");
}
}
// 12. Retrieve the number of rows for the table to be prepared.
public int getRowCount() {
return members != null? rowCount:0;
}
// 13. Similarly, retrieve the column count.
public int getColumnCount() {
return members != null? 3:0;
}
// 14. Retrieve each of the table values at the specified
// row and column.
public Object getValueAt(int row, int column) {
if (directory == null || members == null) {
return null;
}
File fileSysEntity = new File(directory, members[row]);
switch(column) {
case 0:
return fileSysEntity.getName();
case 1:
if (fileSysEntity.isDirectory()) {
return "...";
}
else {
return new Long(fileSysEntity.length());
}
case 2:
return fileSysEntity.isDirectory()? new Boolean(true):
new Boolean(false);
default:
return "";
}
}
// 15. Retrieve the column names to be used in the table header.
public String getColumnName(int column) {
switch(column) {
case 0:
return "Name";
case 1:
return "Bytes";
case 2:
return "Directory";
default:
return "";
}
}
// 16. Retrieve the class types of the entries in
// each of the table columns.
public Class getColumnClass(int column) {
Class returnClass = String.class;
if (column == 2)
returnClass = Boolean.class;
return returnClass;
}
}
Listing 10.4 Table Selections (TTableSelection.java)
// Demonstrates the implementation of table selections.
import javax.swing.*;import javax.swing.table.*;import javax.swing.event.*;import java.awt.*;import java.awt.event.*;public class TTableSelection extends JFrame
implements ListSelectionListener {
Container container;
JTable table;
JScrollPane scrollPane;
JLabel label;
String[] columnTitles = {"A", "B", "C", "D"};
Object[] [] rowData = {
{"11", "12", "13", "14"},
{"21", "22", "23", "24"},
{"31", "32", "33", "34"},
{"41", "42", "44", "44"}};
public TTableSelection() {
// 1. Assign a title to the frame and get
// the handle on its content pane.
super("TTableModel");
container = this.getContentPane();
// 2. Instantiate the label and table objects.
label = new JLabel("", JLabel.CENTER);
table = new JTable(rowData, columnTitles);
// 3. Registering for cell selection.
table.setCellSelectionEnabled(true); // selection enabled
// Obtain a reference to the table selection model
ListSelectionModel cellSelectionModel =
table.getSelectionModel();
// Assign the selection mode.
cellSelectionModel.setSelectionMode(
ListSelectionModel.SINGLE_SELECTION);
// Add the listener to the table selection model.
cellSelectionModel.addListSelectionListener(this);
// 4. Add the panel and table to the container.
container.add(BorderLayout.SOUTH, label);
container.add(new JScrollPane(table));
// 5. Frame settings.
// Add the window closing listener.
addWindowListener(new WindowEventHandler());
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
setBackground(Color.white);
setSize(350, 150); // Frame width=350, height=150
show(); // Display the frame
}
// 6. Window event handler.
class WindowEventHandler extends WindowAdapter {
public void windowClosing(WindowEvent evt) {
System.exit(0);
}
}
// 7. List selection listenter method to be implemented.
public void valueChanged(ListSelectionEvent e) {
int rows, columns;
String selectedData = null;
int[] selectedRow = table.getSelectedRows();
int[] selectedColumns = table.getSelectedColumns();
for (int i=0; i20yrs"};
Object[][] dataEntries = {
{"Saravan", "Pantham", new Integer(50), "B", new Boolean(false)},
{"Eric", "", new Integer(180), "O", new Boolean(true)},
{"John", "", new Integer(120), "AB", new Boolean(false)},
{"Mathew", "", new Integer(140), "A", new Boolean(true)},
};
// 3. Assign the table model object to a table object.
TableModel model = new EditableTableModel(columnTitles, dataEntries);
table = new JTable(model);
table.createDefaultColumnsFromModel();
// 4. Create a combo box and use it as an editor for the
// blood group column.
String[] bloodGroups = {"A", "B", "AB", "O"};
JComboBox comboBox = new JComboBox(bloodGroups);
table.getColumnModel().getColumn(3).setCellEditor(
new DefaultCellEditor(comboBox));
// 5. Add the above panel and table to the container.
container.add(new JScrollPane(table));
// 6. Frame settings.
// Add the window closing listener.
addWindowListener(new WindowEventHandler());
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
setBackground(Color.white);
setSize(450, 150); // Frame width=450, height=150
show(); // Display the frame
}
// 7. Window event handler.
class WindowEventHandler extends WindowAdapter {
public void windowClosing(WindowEvent evt) {
System.exit(0);
}
}
// 8. The main method.
public static void main(String[] args) {
TEditableTable frame = new TEditableTable();
}
}
//
class EditableTableModel extends AbstractTableModel {
String[] columnTitles;
Object[][] dataEntries;
int rowCount;
// 9. Model constructor.
public EditableTableModel(String[] columnTitles, Object[][] dataEntries) {
this.columnTitles = columnTitles;
this.dataEntries = dataEntries;
}
// 10. Retrieve the number of rows for the table to be prepared.
public int getRowCount() {
return dataEntries.length;
}
// 11. Similarly, retrieve the column count.
public int getColumnCount() {
return columnTitles.length;
}
// 12. Retrieve each of the table values at the specified
// row and column.
public Object getValueAt(int row, int column) {
return dataEntries[row][column];
}
// 13. Retrieve the column names to be used in the table header.
public String getColumnName(int column) {
return columnTitles[column];
}
// 14. Retrieve the class types of the entries in
// each of the table columns.
public Class getColumnClass(int column) {
return getValueAt(0, column).getClass();
}
// 15. Allow all the table cells to be editable.
public boolean isCellEditable(int row, int column) {
return true;
}
// 16. Assign the data entered to the data model.
public void setValueAt(Object value, int row, int column) {
dataEntries[row][column] = value;
}
}