TableFilterSelectionVectorPanel
October 20th, 2010package components;
/**
* Created by IntelliJ IDEA.
* User: hamid valizadegan
* Date: Sep 26, 2010
* Time: 3:34:25 AM
*/
import util.Util;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableRowSorter;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
public class TableFilterSelectionVectorPanel extends JPanel {
private boolean DEBUG = true;
private String[] fileds = {};// {"id", "name", "zipcode"};
private JTable table;
private JTextField filterText;
private JTextField statusText;
private TableRowSorter<AbstractTableModel> sorter;
AbstractTableModel model = new javax.swing.table.DefaultTableModel(new Object[][]{}, new String[]{"design Time"});
public JTable getTable() {
return table;
}
public TableFilterSelectionVectorPanel() {
super();
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
Vector dataVector = openTableQuery();
String fileds = Util.fetchGetterFields(dataVector.get(0));
Vector columnNamesVector =Util.stringToArrayVector(fileds, ",");
//Create a table with a sorter.
model = java.beans.Beans.isDesignTime() ? model : new MyTableModel(dataVector, columnNamesVector);
sorter = new TableRowSorter<AbstractTableModel>(model);
table = new JTable(model);
table.setRowSorter(sorter);
table.setPreferredScrollableViewportSize(new Dimension(500, 70));
table.setFillsViewportHeight(true);
//For the purposes of this example, better to have a single
//selection.
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
//When selection changes, provide user with row numbers for
//both view and model.
table.getSelectionModel().addListSelectionListener(
new ListSelectionListener() {
public void valueChanged(ListSelectionEvent event) {
int viewRow = table.getSelectedRow();
if (viewRow < 0) {
//Selection got filtered away.
statusText.setText("");
} else {
int modelRow =
table.convertRowIndexToModel(viewRow);
statusText.setText(
String.format("Selected Row in view: %d. " + "Selected Row in model: %d.", viewRow, modelRow));
}
}
});
//Create the scroll pane and add the table to it.
JScrollPane scrollPane = new JScrollPane(table);
//Add the scroll pane to this panel.
add(scrollPane);
//Create a separate form for filterText and statusText
JPanel form = new JPanel(new SpringLayout());
JLabel l1 = new JLabel("Filter Text:", SwingConstants.TRAILING);
form.add(l1);
filterText = new JTextField();
//Whenever filterText changes, invoke newFilter.
filterText.getDocument().addDocumentListener(
new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
newFilter(filterText.getText());
}
public void insertUpdate(DocumentEvent e) {
newFilter(filterText.getText());
}
public void removeUpdate(DocumentEvent e) {
newFilter(filterText.getText());
}
});
l1.setLabelFor(filterText);
form.add(filterText);
JLabel l2 = new JLabel("Status:", SwingConstants.TRAILING);
form.add(l2);
statusText = new JTextField();
l2.setLabelFor(statusText);
form.add(statusText);
SpringUtilities.makeCompactGrid(form, 2, 2, 6, 6, 6, 6);
add(form);
form.setVisible(!DEBUG);
}
private Vector openTableQuery() {
Vector dataVector=new Vector(3);
dataVector.add(new Student("1","hamid", "valizadegan"));
dataVector.add(new Student("2","jalal", "mashouli"));
dataVector.add(new Student("3","kambiz", "yaghobi"));
return dataVector;
}
public String getFilterText() {
return filterText.getText();
}
public void setFilterText(String filterText) {
this.filterText.setText(filterText);
}
/**
* Update the row filter regular expression from the expression in
* the text box.
*/
private void newFilter(String regex) {
List<RowFilter<AbstractTableModel, Object>> rfs = new ArrayList<RowFilter<AbstractTableModel, Object>>();
RowFilter<AbstractTableModel, Object> rf = RowFilter.regexFilter("", 0);
//If current expression doesn't parse, don't update.
String[] regexes =Util.stringToArraySplit(regex, ",");
for (int i = 0; i < regexes.length; i++) {
try {
if (!regexes[i].isEmpty()) {
rf = RowFilter.regexFilter(regexes[i], i);
rfs.add(rf);
}
} catch (java.util.regex.PatternSyntaxException e) {
return;
}
}
if (rf == null) {
return;
}
rf = RowFilter.andFilter(rfs);
sorter.setRowFilter(rf);
}
private String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public int getIdIndexColumn() {
return model.findColumn(id);
}
public String[] getFileds() {
return fileds;
}
public void setFileds(String[] fileds) {
this.fileds = fileds;
}
public boolean isRecordSelected() {
return table.getSelectedRow() != -1;
}
public Object getSelectedID() {
int col = model.findColumn(id);
int row = table.getSelectedRow();
if (row != -1 && col != -1) {
return table.getValueAt(row, col);
}
return null;
}
class MyTableModel extends AbstractTableModel { //DefaultTableModel { //
Vector rowDataVector;
Vector columnNamesVector;
public MyTableModel() {
}
public MyTableModel(Vector newData, Vector colNames) {
setDataVector(newData,colNames);
}
public void setDataVector(Vector newData, Vector colNames) {
rowDataVector=newData;
columnNamesVector=colNames;
fireTableDataChanged();
}
public int getColumnCount() {
return columnNamesVector.size();
}
public int getRowCount() {
return rowDataVector.size();
}
public String getColumnName(int col) {
return (String)columnNamesVector.get(col);
}
public Object getValueAt(int row, int col) {
return Util.execGetMethod(rowDataVector.get(row), getColumnName(col));
}
/*
* JTable uses this method to determine the default renderer/
* editor for each cell. If we didn't implement this method,
* then the last column would contain text ("true"/"false"),
* rather than a check box.
*/
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
/*
* Don't need to implement this method unless your table's
* editable.
*/
public boolean isCellEditable(int row, int col) {
//Note that the data/cell address is constant,
//no matter where the cell appears onscreen.
if (col < 2) {
return false;
} else {
return true;
}
}
/*
* Don't need to implement this method unless your table's
* data can change.
*/
public void setValueAt(Object value, int row, int col) {
if (DEBUG) {
System.out.println("Setting value at " + row + "," + col
+ " to " + value
+ " (an instance of "
+ value.getClass() + ")");
}
//data[row][col] = value;
Util.execSetMethod(rowDataVector.get(row), getColumnName(col),new Object[]{value});
fireTableCellUpdated(row, col);
if (DEBUG) {
System.out.println("New value of data:");
printDebugData();
}
}
private void printDebugData() {
int numRows = getRowCount();
int numCols = getColumnCount();
for (int i = 0; i < numRows; i++) {
System.out.print(" row " + i + ":");
for (int j = 0; j < numCols; j++) {
System.out.print(" " + getValueAt(i,j));
}
System.out.println();
}
System.out.println("--------------------------");
}
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("TableFilterDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
TableFilterSelectionVectorPanel newContentPane = new TableFilterSelectionVectorPanel();
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
new JTable(new Vector(),new Vector() );
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
Attachments:
TableFilterDemo.zip (15 KB)