How to implement Lucene TableSearch with jTable - java

I have been reading and searching for quite some time and can't seem to wrap my head around how to use Lucene in my Java program that contains a jTable.
What I want to be able to do is search the table when submitting a new row entry. Do I simply create a TableModel from my jTable and pass it into the TableSearcher constructor if I include the 3.3 Lucene jar file in my path? I have included some of my code...please, I welcome any direction! Thanks.
Here is my method for populating my jTable from data stored in vectors:
...
public static boolean hasSearchResults = false;
public String selectedRequirementName;
public TableSearcher ts;
DefaultTableModel sc;
public TablePanel(int z, String name, String reason) { //pulls in panel number, project name, and whether the project was new or opened, from the MainGUI class
initComponents();
sc=(DefaultTableModel) reqTable.getModel();
ts = new TableSearcher(sc);
aProject = new Project(reason, name); //calls Project class to control the project
try{
requirementsVector = new Vector(aProject.getRequirementsList());
requirementsList =new String[requirementsVector.size()];
for(int i=0; i < requirementsVector.size(); i++){
requirementsList[i] = requirementsVector.get(i).getName();
System.out.println(requirementsList[i]);
sc.addRow(new Object[]{
requirementsVector.get(i).getName(),
requirementsVector.get(i).getDefinition(),
requirementsVector.get(i).getType(),
requirementsVector.get(i).getPriority(),
requirementsVector.get(i).getAssigned(),
requirementsVector.get(i).getDue(),
requirementsVector.get(i).getStatus()});
//this.editingProjectName = name;
}
}catch(NullPointerException e1){
System.out.println(e1);
} ....
Here is my code that inserts a new row into the jTable:
private void ConfirmActionPerformed(java.awt.event.ActionEvent evt) {
String ReqName = nameTextField.getText();
String ReqDescription = descriptionTextField.getText();
String Type = (String)jType.getSelectedItem();
String Priority = (String)PriorityComboBox.getSelectedItem();
String Assigned = (String)jDateAssignedMonth.getSelectedItem() + "/" + (String)jDateAssignedDay.getSelectedItem() + "/" + (String)jDateAssignedYear.getSelectedItem();
String Due = (String)jDateDueMonth.getSelectedItem() + "/" + (String)jDateDueDay.getSelectedItem() + "/" + (String)jDateDueYear.getSelectedItem();
String Status = (String)jStatus.getSelectedItem();
// search string pass to TableSearcher
ts.search(ReqDescription);
if (editingaRow == false && !hasSearchResults){
sc.addRow(new Object[]{
ReqName,ReqDescription,Type,Priority,Assigned, Due, Status
});
requirementsVector.add(new Requirement(ReqName, ReqDescription, Type, Priority, Assigned, Due,Status));
aProject.saveRevision(requirementsVector, name);
}else if (editingaRow == true){
sc.setValueAt(ReqName,selectedRow,0);
sc.setValueAt(ReqDescription,selectedRow,1);
sc.setValueAt(Type,selectedRow,2);
sc.setValueAt(Priority,selectedRow,3);
sc.setValueAt(Assigned,selectedRow,4);
sc.setValueAt(Due,selectedRow,5);
sc.setValueAt(Status,selectedRow,6);
requirementsVector.setElementAt(new Requirement(ReqName, ReqDescription, Type, Priority, Assigned, Due,Status),(selectedRow));
aProject.saveRevision(requirementsVector, name);
editingaRow = false;
}
disableRequirementEditor();
newReq.setEnabled(true);
reqTable.clearSelection();
}
And here is the TableSearcher model that I am using (I added new functionality to the search method). What is happening is when I enter a new entry, the search finds that entry as a duplicate and returns it in my jFrame I implement within search method of the TableSearcher. This only happens with a unique entry that has no match in the indexed table. If there is a search result in the index that matches my new entry, then only the existing entry displays in my jFrame, not the new one I am attempting.
// provided by Jonathan Simon <jonathan_s_simon#yahoo.com>
class TableSearcher extends AbstractTableModel {
/**
* The inner table model we are decorating
*/
protected TableModel tableModel;
/**
* This listener is used to register this class as a listener to
* the decorated table model for update events
*/
private TableModelListener tableModelListener;
/**
* these keeps reference to the decorated table model for data
* only rows that match the search criteria are linked
*/
private ArrayList rowToModelIndex = new ArrayList();
//Lucene stuff.
/**
* In memory lucene index
*/
private RAMDirectory directory;
/**
* Cached lucene analyzer
*/
private Analyzer analyzer;
/**
* Links between this table model and the decorated table model
* are maintained through links based on row number. This is a
* key constant to denote "row number" for indexing
*/
private static final String ROW_NUMBER = "ROW_NUMBER";
/**
* Cache the current search String. Also used internally to
* key whether there is an active search running or not. i.e. if
* searchString is null, there is no active search.
*/
private String searchString = null;
/**
* #param tableModel The table model to decorate
*/
public TableSearcher(TableModel tableModel) {
analyzer = new WhitespaceAnalyzer();
tableModelListener = new TableModelHandler();
setTableModel(tableModel);
tableModel.addTableModelListener(tableModelListener);
clearSearchingState();
}
/**
*
* #return The inner table model this table model is decorating
*/
public TableModel getTableModel() {
return tableModel;
}
/**
* Set the table model used by this table model
* #param tableModel The new table model to decorate
*/
public final void setTableModel(TableModel tableModel) {
//remove listeners if there...
if (this.tableModel != null) {
this.tableModel.removeTableModelListener(tableModelListener);
}
this.tableModel = tableModel;
if (this.tableModel != null) {
this.tableModel.addTableModelListener(tableModelListener);
}
//recalculate the links between this table model and
//the inner table model since the decorated model just changed
reindex();
// let all listeners know the table has changed
fireTableStructureChanged();
}
/**
* Reset the search results and links to the decorated (inner) table
* model from this table model.
*/
private void reindex() {
try {
// recreate the RAMDirectory
directory = new RAMDirectory();
IndexWriter writer = new IndexWriter(directory, analyzer, true, IndexWriter.MaxFieldLength.UNLIMITED);
// iterate through all rows
for (int row=0; row < tableModel.getRowCount(); row++){
//for each row make a new document
Document document = new Document();
//add the row number of this row in the decorated table model
//this will allow us to retrive the results later
//and map this table model's row to a row in the decorated
//table model
document.add(new Field(ROW_NUMBER, "" + row, Field.Store.YES, Field.Index.ANALYZED));
//iterate through all columns
//index the value keyed by the column name
//NOTE: there could be a problem with using column names with spaces
for (int column=0; column < tableModel.getColumnCount(); column++){
String columnName = tableModel.getColumnName(column);
String columnValue = String.valueOf(tableModel.getValueAt(row, column)).toLowerCase();
document.add(new Field(columnName, columnValue, Field.Store.YES, Field.Index.ANALYZED));
}
writer.addDocument(document);
}
writer.optimize();
writer.close();
} catch (Exception e){
e.printStackTrace();
}
}
/**
* #return The current lucene analyzer
*/
public Analyzer getAnalyzer() {
return analyzer;
}
/**
* #param analyzer The new analyzer to use
*/
public void setAnalyzer(Analyzer analyzer) {
this.analyzer = analyzer;
//reindex from the model with the new analyzer
reindex();
//rerun the search if there is an active search
if (isSearching()){
search(searchString);
}
}
/**
* Run a new search.
*
* #param searchString Any valid lucene search string
*/
public void search(String searchString){
// to store row numbers of results rows to display later
Vector<String> rowNums = new Vector();
//if search string is null or empty, clear the search == search all
if (searchString == null || searchString.equals("")){
clearSearchingState();
fireTableDataChanged();
return;
}
try {
//cache search String
this.searchString = searchString;
//make a new index searcher with the in memory (RAM) index.
IndexSearcher is = new IndexSearcher(directory);
//make an array of fields - one for each column
String[] fields = new String[tableModel.getColumnCount()];
for (int t=0; t<tableModel.getColumnCount(); t++){
fields[t]=tableModel.getColumnName(t);
}
//build a query based on the fields, searchString and cached analyzer
//NOTE: This is an area for improvement since the MultiFieldQueryParser
// has some weirdness.
MultiFieldQueryParser parser = new MultiFieldQueryParser(fields, analyzer);
Query query = parser.parse(searchString);
//run the search
Hits hits = is.search(query);
for (int t=0; t<hits.length(); t++){
Document document = hits.doc(t);
Fieldable field = document.getField(ROW_NUMBER);
// adding row numbers to vector
rowNums.add(field.stringValue());
}
// trying to display search results in new table
if(!rowNums.isEmpty()){
TablePanel.hasSearchResults = true;
for (int v=0; v<rowNums.size(); v++){
System.out.println("Match in row number " + rowNums.elementAt(v));
}
JFrame frame = new JFrame("Possible Duplicates");
String colNames[] = {"Name", "Definition", "Type", "Priority", "Date Assigned", "Due Date", "Status"};
DefaultTableModel dtm = new DefaultTableModel(null,colNames);
for (int r = 0; r<rowNums.size(); r++){
String ReqName = (String) tableModel.getValueAt(Integer.parseInt(rowNums.elementAt(r)), 0);
String ReqDescription = (String) tableModel.getValueAt(Integer.parseInt(rowNums.elementAt(r)), 1);
String Type = (String) tableModel.getValueAt(Integer.parseInt(rowNums.elementAt(r)), 2);
String Priority = (String) tableModel.getValueAt(Integer.parseInt(rowNums.elementAt(r)), 3);
String Assigned = (String) tableModel.getValueAt(Integer.parseInt(rowNums.elementAt(r)), 4);
String Due = (String) tableModel.getValueAt(Integer.parseInt(rowNums.elementAt(r)), 5);
String Status = (String) tableModel.getValueAt(Integer.parseInt(rowNums.elementAt(r)), 6);
dtm.addRow(new Object[]{
ReqName,ReqDescription,Type,Priority,Assigned, Due, Status
});
}
JTable tblResults = new JTable(dtm);
JScrollPane sp = new JScrollPane(tblResults);
JPanel panel = new JPanel(new BorderLayout());
panel.setPreferredSize(new Dimension(900,300));
panel.add(sp,BorderLayout.CENTER);
panel.add(new JLabel("Possible Duplicates",JLabel.CENTER),BorderLayout.SOUTH);
JOptionPane.showConfirmDialog(null,panel);
}
//reset this table model with the new results
resetSearchResults(hits);
} catch (Exception e){
e.printStackTrace();
}
//notify all listeners that the table has been changed
fireTableStructureChanged();
}
/**
*
* #param hits The new result set to set this table to.
*/
private void resetSearchResults(Hits hits) {
try {
//clear our index mapping this table model rows to
//the decorated inner table model
rowToModelIndex.clear();
//iterate through the hits
//get the row number stored at the index
//that number is the row number of the decorated
//tabble model row that we are mapping to
for (int t=0; t<hits.length(); t++){
Document document = hits.doc(t);
Fieldable field = document.getField(ROW_NUMBER);
rowToModelIndex.add(new Integer(field.stringValue()));
System.out.println("Something " + rowToModelIndex.add(new Integer(field.stringValue())));
clearSearchingState();
}
} catch (Exception e){
e.printStackTrace();
}
}
private int getModelRow(int row){
return ((Integer) rowToModelIndex.get(row)).intValue();
}
/**
* Clear the currently active search
* Resets the complete dataset of the decorated
* table model.
*/
private void clearSearchingState(){
searchString = null;
rowToModelIndex.clear();
for (int t=0; t<tableModel.getRowCount(); t++){
rowToModelIndex.add(new Integer(t));
}
}
// TableModel interface methods
public int getRowCount() {
return (tableModel == null) ? 0 : rowToModelIndex.size();
}
public int getColumnCount() {
return (tableModel == null) ? 0 : tableModel.getColumnCount();
}
public String getColumnName(int column) {
return tableModel.getColumnName(column);
}
public Class getColumnClass(int column) {
return tableModel.getColumnClass(column);
}
public boolean isCellEditable(int row, int column) {
return tableModel.isCellEditable(getModelRow(row), column);
}
public Object getValueAt(int row, int column) {
return tableModel.getValueAt(getModelRow(row), column);
}
public void setValueAt(Object aValue, int row, int column) {
tableModel.setValueAt(aValue, getModelRow(row), column);
}
private boolean isSearching() {
return searchString != null;
}
private class TableModelHandler implements TableModelListener {
public void tableChanged(TableModelEvent e) {
// If we're not searching, just pass the event along.
if (!isSearching()) {
clearSearchingState();
reindex();
fireTableChanged(e);
return;
}
// Something has happened to the data that may have invalidated the search.
reindex();
search(searchString);
fireTableDataChanged();
return;
}
}

It looks like your code doesn't index the table data with Lucene. One easy way to do this is to make your own table model that indexes internally, with an exposed search function that you can connect to limit the data displayed. This is what I wrote about in Swing Hacks a few years back.
Without the indexing, Lucene won't just automatically 'work' because it's in your classpath.
Jonathan

take a look at the very simple example
in your case, you would do something like this to create the document, that would get saved in the index.
this code is not complete or necessarily error free,; but is more of a starting point to get you going
Document doc = new Document();
doc.add(new Field("ReqName", ReqName, Field.Store.YES, Field.Index.NOT_ANALYZED));
doc.add(new Field("ReqDescription", ReqDescription, Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("Type", Type, Field.Store.YES, Field.Index.NOT_ANALYZED));
doc.add(new Field("Priority", Priority, Field.Store.YES, Field.Index.NOT_ANALYZED));
doc.add(new Field("Assigned", Assigned, Field.Store.YES, Field.Index.NOT_ANALYZED));
doc.add(new Field("Due", Due, Field.Store.YES, Field.Index.NOT_ANALYZED));
doc.add(new Field("Status", Status, Field.Store.YES, Field.Index.NOT_ANALYZED));
writer.addDocument(doc);
writer.close();

Related

How can I duplicate a table in word with apache poi? [duplicate]

I have a table in the docx template.
Depending on the number of objects, I have to duplicate the table as many times as I have objects. Duplicate tables must be after the table from the template.
I have several tables in the template that should behave like this.
XmlCursor take the place of the first table from the template and put the next one there. I want to insert the next table after the previous one, which I added myself, but xmlcursor does not return the table item I added, but returns "STARTDOC"
XmlCursor cursor = docx.getTables().get(pointer).getCTTbl().newCursor();
cursor.toEndToken();
while (cursor.toNextToken() != XmlCursor.TokenType.START) ;
XWPFParagraph newParagraph = docx.insertNewParagraph(cursor);
newParagraph.createRun().setText("", 0);
cursor.toParent();
cursor.toEndToken();
while (cursor.toNextToken() != XmlCursor.TokenType.START) ;
docx.insertNewTbl(cursor);
CTTbl ctTbl = CTTbl.Factory.newInstance();
ctTbl.set(docx.getTables().get(numberTableFromTemplate).getCTTbl());
XWPFTable tableCopy = new XWPFTable(ctTbl, docx);
docx.setTable(index + 1, tableCopy);
Not clear what you are aiming for with the cursor.toParent();. And I also cannot reproduce the issue having only your small code snippet. But having a complete working example may possible help you.
Assuming we have following template:
Then following code:
import java.io.FileOutputStream;
import java.io.FileInputStream;
import org.apache.poi.xwpf.usermodel.*;
import org.apache.xmlbeans.XmlObject;
import org.apache.xmlbeans.XmlCursor;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTbl;
public class WordCopyTableAfterTable {
static XmlCursor setCursorToNextStartToken(XmlObject object) {
XmlCursor cursor = object.newCursor();
cursor.toEndToken(); //Now we are at end of the XmlObject.
//There always must be a next start token.
while(cursor.hasNextToken() && cursor.toNextToken() != org.apache.xmlbeans.XmlCursor.TokenType.START);
//Now we are at the next start token and can insert new things here.
return cursor;
}
static void removeCellValues(XWPFTableCell cell) {
for (XWPFParagraph paragraph : cell.getParagraphs()) {
for (int i = paragraph.getRuns().size()-1; i >= 0; i--) {
paragraph.removeRun(i);
}
}
}
public static void main(String[] args) throws Exception {
//The data. Each row a new table.
String[][] data= new String[][] {
new String[] {"John Doe", "5/23/2019", "1234.56"},
new String[] {"Jane Doe", "12/2/2019", "34.56"},
new String[] {"Marie Template", "9/20/2019", "4.56"},
new String[] {"Hans Template", "10/2/2019", "4567.89"}
};
String value;
XWPFDocument document = new XWPFDocument(new FileInputStream("WordTemplate.docx"));
XWPFTable tableTemplate;
CTTbl cTTblTemplate;
XWPFTable tableCopy;
XWPFTable table;
XWPFTableRow row;
XWPFTableCell cell;
XmlCursor cursor;
XWPFParagraph paragraph;
XWPFRun run;
//get first table (the template)
tableTemplate = document.getTableArray(0);
cTTblTemplate = tableTemplate.getCTTbl();
cursor = setCursorToNextStartToken(cTTblTemplate);
//fill in first data in first table (the template)
for (int c = 0; c < data[0].length; c++) {
value = data[0][c];
row = tableTemplate.getRow(1);
cell = row.getCell(c);
removeCellValues(cell);
cell.setText(value);
}
paragraph = document.insertNewParagraph(cursor); //insert new empty paragraph
cursor = setCursorToNextStartToken(paragraph.getCTP());
//fill in next data, each data row in one table
for (int t = 1; t < data.length; t++) {
table = document.insertNewTbl(cursor); //insert new empty table at position t
cursor = setCursorToNextStartToken(table.getCTTbl());
tableCopy = new XWPFTable((CTTbl)cTTblTemplate.copy(), document); //copy the template table
//fill in data in tableCopy
for (int c = 0; c < data[t].length; c++) {
value = data[t][c];
row = tableCopy.getRow(1);
cell = row.getCell(c);
removeCellValues(cell);
cell.setText(value);
}
document.setTable(t, tableCopy); //set tableCopy at position t instead of table
paragraph = document.insertNewParagraph(cursor); //insert new empty paragraph
cursor = setCursorToNextStartToken(paragraph.getCTP());
}
paragraph = document.insertNewParagraph(cursor);
run = paragraph.createRun();
run.setText("Inserted new text below last table.");
cursor = setCursorToNextStartToken(paragraph.getCTP());
FileOutputStream out = new FileOutputStream("WordResult.docx");
document.write(out);
out.close();
document.close();
}
}
leads to following result:
Is that about what you wanted to achieve?
Please note how I insert the additional tables.
Using table = document.insertNewTbl(cursor); a new empty table is inserted at position t. This table is placed into the document body. So this table must be taken for adjusting the cursor.
Then tableCopy = new XWPFTable((CTTbl)cTTblTemplate.copy(), document); copys the template table. Then this copy is filled with data. And then it is set into the document at position t using document.setTable(t, tableCopy);.
Unfortunately apache poi is incomplete here. XWPFDocument.setTable only sets the internally ArrayLists but not the underlying XML. XWPFDocument.insertNewTbl sets the underlying XML but only using an empty table. So we must do it that ugly complicated way.

How to wrap the content inside table cell without data loss and extension of the table width using iText 7 and Java

Table width goes beyond the right margin and some content inside table cell is lost when there is bigger word(continuous text) present.
Below code implemented to print table
public Table createTable(Document doc, UnitValue[] columnsWidth) {
Table table = new Table(columnsWidth);
table.setBorder(new SolidBorder(0.9f));
float tableWidth = doc.getPdfDocument().getDefaultPageSize().getWidth()-(doc.getLeftMargin()+doc.getRightMargin());
table.setWidth(tableWidth);
return table;
}
public void addTable(Document doc, AbstractElement<?> parent, Table table) {
if(parent == null){
table.setMarginTop(2f);
doc.add(table);
}
}
UnitValue percentageUnit = new UnitValue(2, 1.00f);
UnitValue[] percentageUnitArr = new UnitValue[2];
percentageUnitArr[0] = percentageUnit;
percentageUnitArr[] = percentageUnit;
Table table = createTable(doc, percentageUnitArr);
addTable(doc, iTextParent, table);

JTable showing only 1 row despite having more than 1 row count

I'm trying to load some data from a database (I use Oracle's SQL Developer) into a JTable in java. I put the data from the database in a Vector of Vector, this is my load method which I put in a class called DBJobs:
public Vector load() {
try {
Vector tableData = new Vector();
Conn con = new Conn();
con.openConn();
con.statement = con.dbConn.createStatement();
ResultSet rs = con.statement.executeQuery("Select * from Jobs");
while (rs.next()) {
Vector<Object> row = new Vector<Object>();
row.add(rs.getString("Job_ID"));
row.add(rs.getString("Job_Title"));
row.add(rs.getString("Parent_Job_ID_1"));
row.add(rs.getString("Parent_Job_ID_2"));
row.add(rs.getString("Description"));
tableData.add(row);
}
con.closeConn();
return tableData;
} catch (SQLException ex) {
ex.printStackTrace();
return null;
}
}
Then I tried populating them into a JTable which I've made with an editor in another class:
private void populateJobsTable() {
Vector<String> tableHeader = new Vector<String>();
tableHeader.add("Job ID");
tableHeader.add("Job Name");
tableHeader.add("Parent Job ID 1");
tableHeader.add("Parent Job ID 2");
tableHeader.add("Description");
Vector tableData = dbJobs.load();
tblJobs.setModel(new DefaultTableModel(tableData, tableHeader));
}
But all I can see is 1 row of data in the table. I've tried printing how many data the Vector has and how many rows the Table has and they're both returning 49, which is the amount of data I have in my database. So why is my table only showing 1 data?
Edit:
I think this is the code generated to make the JTable:
tblJobs = new javax.swing.JTable();
tblJobs.setFont(new java.awt.Font("Tempus Sans ITC", 0, 14)); // NOI18N
tblJobs.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null}
},
new String [] {
"Job Name"
}
) {
Class[] types = new Class [] {
java.lang.String.class
};
boolean[] canEdit = new boolean [] {
false
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
tblJobs.setPreferredSize(new java.awt.Dimension(225, 16));
jScrollPane5.setViewportView(tblJobs);
if (tblJobs.getColumnModel().getColumnCount() > 0) {
tblJobs.getColumnModel().getColumn(0).setResizable(false);
}
First of all that is NOT a MCVE. How is that code complete? How can we compile and test that code? Did you not read my comment???
I would suggest you get rid of the IDE and learn how to create GUIs manually. What is the point of the IDE generating JTable with a custom TableModel. That code is completely useless since you then use create your own TableModel and use the setModel(...) method which will replace the model created by the IDE.
tblJobs.setPreferredSize(new java.awt.Dimension(225, 16));
The above code looks suspicious. You should not be setting a preferred size on a Swing component. The size of the table looks like it will only display one row at a time.
It that is not the problem then I will have no more suggestion until a proper MCVE is posted. Every question should have a MCVE so we don't spend time guessing what you may or may not be doing.

Can't get Object string value; need to convert to String to compare

I want to check if the value does exist or not in Tree when trying to add node from Tree. The value does not match in the case that I got Object instead of String.
Here is the action code for calling existsInTable()
try {
DefaultMutableTreeNode selectedElement = (DefaultMutableTreeNode) TestTree.getSelectionPath().getLastPathComponent();
Object[] row = {selectedElement};
DefaultTableModel model = (DefaultTableModel) myTests_table.getModel();
if (selectedElement.isLeaf() == true && existsInTable(myTests_table, row) == false) {
model.addRow(row);
} else {
JOptionPane.showMessageDialog(null, "Please Choose Test name!", "Error", JOptionPane.WARNING_MESSAGE);
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Error");
}
Here are the check method
public boolean existsInTable(JTable table, Object[] testname) {
int row = table.getRowCount();
for (int i = 0; i < row; i++) {
String str = "";
str = table.getValueAt(i, 0).toString();
if (testname.equals(str)) {
System.out.println(str);
JOptionPane.showMessageDialog(null, "data alreadyexist.", "message", JOptionPane.PLAIN_MESSAGE);
return true;
}
}
return false;
}
the result is this : [Ljava.lang.Object;#11da1f8
but it should be : Test
If you add an instance of Object to your TableModel, that is what getValueAt() will return. Given an Object, the result returned by toString() is entirely expected—"a string consisting of the name of the class of which the object is an instance, the at-sign character #, and the unsigned hexadecimal representation of the hash code of the object."
Looking closer, you appear to have added an array of Object instances. Given a default table model,
DefaultTableModel model = new DefaultTableModel(1, 1);
the following lines
model.setValueAt(new Object[1], 0, 0);
System.out.println(model.getValueAt(0, 0));
produce this output:
[Ljava.lang.Object;#330bedb4
To see a string, such as "Test", add a corresponding instance of String to your TableModel:
model.setValueAt("Test", 0, 0);
System.out.println(model.getValueAt(0, 0));
which produces the desired output:
Test
For best results, verify that your implementation of getColumnClass() is compatible, as suggested in How to Use Tables: Concepts: Editors and Renderers.

JFace ViewerFilter Table

I have problem regarding my Filtering of my Table. I'm using a ViewerFilter and override the select Method to fitler that Table. The Filtertext itself is entered via a Textfield.
So now to my problem. For example my table looks like the following:
column
123
124
In my textfield the user can enter the columnname=data1,data2 to show all rows which have either data1 or data2 as data. so in my above example if the user enters column=123,124 both rows should still be visible. The problem here is that I refresh my tableviewer after each entered character. So when the user enters column=123 the Table only shows one column. When adding ,124 to the filtertext I filter my already filtered table. So no data gets shown at the end. How can I still filter the original Tabledata?
#Override
public boolean select(final Viewer viewer, final Object parentElement, final Object element) {
final String filterString = filterText.getText().toLowerCase();
if (filterString.length() == 0) { return true; }
final mydata myData= (mydata) element;
if (filterString.matches("columnName" + ".+")) {
index = filterString.indexOf("columnName" + ".+");
evaluateText(myData, filterString, i, index + tableColumnsText[i].length())
}
public boolean evaluateText(final mydata data, final String filterText, final int beginningIndex) {
subString = filterText.substring(beginningIndex, filterText.length());
return evaluateString(data.getString(), subString);
}
public boolean evaluateString(final String cellString, final String commaString) {
int countSubstrings = 0;
final String[] items = commaString.split(",");
countSubstrings = items.length;
for (final String s : items) {
if (s.length() != 0) {
if (!cellString.contains(s)) { return false; }
}
}
return true;
}
So I tried to filter out the main components of the method. Can I somehow access the unfiltered table?

Categories

Resources