Hi guys, If you are looking for a search and replace program like the one provided by MS Office, Dreamweaver, and every other High end application, then you have come to the right place. The following code will help you to search a particular string or a word in a JTable.
If you are developing something like a spreadsheet or excel sheet in java, then this will surely help you in searching those big documents, or 2D arrays.
You can customize it for search and replace as well.
CODE
import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.print.*;
import java.text.*;
import javax.swing.BorderFactory;
import javax.swing.border.Border;
import java.util.Calendar;
import javax.swing.table.*;
import java.awt.*;
import java.awt.print.*;
import java.awt.geom.*;
import java.text.MessageFormat;
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
import java.awt.print.*;
import java.io.*;
class MatCell
{
int row=0;
int col=0;
};
public class TablePrint
{
//Printable tp;
static String ovr=”";
int drow,arow;
TableColumn cl;
static void printFrame(Object rs[][],Object hd[],String m)
{
final String mm=m;
final Object rows[][]=rs;
final Object headers[] = hd;
Runnable runner = new Runnable() {
public void run() {
final JFrame frame = new JFrame(“Convergence Printing. www.convergenceservices.in”);
DefaultTableModel model = new DefaultTableModel(rows,headers);
final JTable table = new JTable( model )
{
// Returning the Class of each column will allow different
// renderers to be used based on Class
public Class getColumnClass(int column)
{
return getValueAt(0, column).getClass();
}
};
table.setPreferredScrollableViewportSize(table.getPreferredSize());
table.setShowGrid(false);
table.setSize(620,500);
table.setShowHorizontalLines(false);
table.setShowVerticalLines(false);
table.setAutoResizeMode(JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS);
if(mm.equalsIgnoreCase(“1″)) // for receipts
{
final JTextField search=new JTextField(10);
JPanel p=new JPanel();
JButton button1 = new JButton(“Find next”);
ActionListener findAction = new ActionListener() {
int startrow=0;
int startcol=0;
public void actionPerformed(ActionEvent e)
{
String mat[][]=getStringArray(table);
/* for (int i=0;i<mat.length ;i++ )
{
for (int j=0;j<mat[0].length ;j++ )
{
System.out.print(“\t”+mat[i][j]);
}
System.out.println();
}
*/ String key = search.getText();
MatCell m= contains (key, mat, startrow,startcol);
if (m!=null)
{
search.setBackground(Color.white);
startrow=m.row;
startcol=m.col;
System.out.println(“Row=”+startrow);
System.out.println(“Col=”+startcol);
boolean toggle = false;
boolean extend = false;
table.changeSelection(startrow, startcol, toggle, extend);
// startrow+=(m.row+1)%mat[0].length;
startcol=(m.col+1)%mat[0].length;
if (startcol==0)
{
startrow++;
}
System.out.println(” New Row=”+startrow);
System.out.println(” New Col=”+startcol);
}
else
{
startrow=0;
startcol=0;
table.clearSelection();
search.setBackground(Color.red);
Toolkit.getDefaultToolkit().beep();
}
//If a string was returned, say so.
}
public MatCell contains(String search, String[][] searchtable,int row,int cell)
{
boolean found = false;
boolean searchrow = true;
int cellcounter = 0;
int cellcount =0;
try
{
cellcount = searchtable[0].length;
}
catch (ArrayIndexOutOfBoundsException e)
{
// if the array is not initialised
cellcount = 0;
System.out.println(“Array not initialised”);
}
// int row = 0;
// int cell = 0;
int ROWDIM=searchtable.length-1;
int[] cellhit = new int[ROWDIM];
while(!found)
{
MatCell mat=new MatCell();
while(searchrow)
{
if(cellcount == cell)
{
cell = 0;
searchrow = false;
}
else
{
//System.out.println(“Array value:”+searchtable[row][cell]);
if(searchtable[row][cell]!=null)
{
if((searchtable[row][cell]).toLowerCase().contains(search.toLowerCase()))
{
mat.row=row;
mat.col=cell;
// System.out.println(“Found “+searchtable[row][cell]);
found = true;
return(mat);
}
}
cell++;
}
}
row++;
searchrow = true;
if(row==ROWDIM)
{
System.out.println(“Search not found.”);
found = true; // return true value to break the loop;
}
}
return null;
}
public String[][] getStringArray(JTable jt)
{
String s[][]=new String[jt.getRowCount()][jt.getColumnCount()];
for (int i=0;i<s.length ;i++ )
{
for (int j=0;j<s[0].length ;j++ )
{
s[i][j]=”"+jt.getValueAt(i,j);
}
}
return s;
}
};
button1.addActionListener(findAction);
search.addActionListener(findAction);
p.add(search);
p.add(button1);
button1.setMnemonic (KeyEvent.VK_F);
frame.add(p, BorderLayout.NORTH);
boolean opt=true;
String str=”";
try {
BufferedReader in = new BufferedReader(new FileReader(“printoption.bat”));
String str1=”";
while ((str1 = in.readLine()) != null) {
str=str1;
}
in.close();
} catch (IOException e) {
}
System.out.println(“str=”+str);
if (str.equalsIgnoreCase(“use”))
{
opt=true;
}
else
{
opt=false;
}
opt=true;
int vColIndex1 = 0;
if (opt)
{
table.getColumnModel().getColumn(vColIndex1).setHeaderValue(new ImageIcon(“images/logo.jpg”));
table.getColumnModel().getColumn(vColIndex1).setHeaderRenderer(new TableCellRenderer());
}
int width1 = 500;
table.getColumnModel().getColumn(vColIndex1).setPreferredWidth(width1);
table.setRowHeight(20);
frame.setBounds(400,35,620, 550);
}
JScrollPane scrollPane = new JScrollPane(table);
frame.add(scrollPane, BorderLayout.CENTER);
JButton button = new JButton(“Print”);
ActionListener printAction = new ActionListener() {
public void actionPerformed(ActionEvent e)
{
table.clearSelection();
try{
//JTable table = new JTable(myModel);
PrinterJob job =PrinterJob.getPrinterJob();
MessageFormat headerFormat = new MessageFormat(“”);
MessageFormat footerFormat = new MessageFormat(“”);
Paper pap=new Paper();
pap.setImageableArea(0,500,468,771);
PageFormat pg=job.defaultPage();
pg.setPaper(pap);
System.out.println(“Width=”+pg.getImageableWidth());
System.out.println(“Height=”+pg.getImageableHeight());
Printable tp=new TablePrintable1(table,JTable.PrintMode.FIT_WIDTH, headerFormat,footerFormat);
job.setPrintable(tp,pg);
if (job.printDialog())
{
job.setJobName(“Theo Printing”);
job.print();
}
}
catch (PrinterException pe)
{System.err.println(“Error printing: “);}
frame.dispose();
}
};
button.addActionListener(printAction);
button.setMnemonic (KeyEvent.VK_P);
frame.add(button, BorderLayout.SOUTH);
frame.setVisible(true);
frame.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
frame.setLocationRelativeTo(null);
}
};
EventQueue.invokeLater(runner);
ovr=”1″;
}
public static void main(String arg[])
{
Calendar c=Calendar.getInstance();
Object chargedata[][]=new Object[16][1];
for (int j=0;j<chargedata.length ;j++ )
{
chargedata[j][0]=”";
// chargedata[j][1]=”";
}
int j=0;
chargedata[j++][0]=”";
chargedata[j++][0]=”<html><h3>Transaction id : Receipt Date : “+c.get(Calendar.DAY_OF_MONTH)+”-”+(c.get(Calendar.MONTH)+1)+”-”+c.get(Calendar.YEAR)+” </h3></html>”;
chargedata[j++][0]=” “;
chargedata[j++][0]=”RECEIVED with thanks from”;
chargedata[j++][0]=”<html><h4>Mr./Mrs./Ms </h4></html>”;
chargedata[j++][0]=”<html><h4>Rs. only, by </h4><html>”;
chargedata[j++][0]=”towards the following “;
chargedata[j++][0]=”<html><h4> Particulars INR </h4></html>”;
//added for theo
chargedata[j++][0]=”<html><h4>———————————————————————————————————————————————————————–</h4></html>”;
chargedata[j++][0]=”Pooja Offering “;
chargedata[j++][0]=”<html><h4>———————————————————————————————————————————————————————–</h4></html>”;
chargedata[j++][0]=”<html><h3>Date of Pooja : . Time (24 hrs): </h3></html>”;
chargedata[j++][0]=”<html><h6>*Cheque subject to realisation</h6></html>”;
chargedata[j++][0]=”";
chargedata[j++][0]=”";
chargedata[j++][0]=”<html><h4> Treasurer </h4></html>”;
String hd[]={“”};
TablePrint.printFrame(chargedata,hd,”1″);
}
///////////////////————————–
}
OUTPUT
