I am making a java app where user can search for data in the JTable. I have used filters to let user search content from the JTable. I also intend on exporting the filtered data to a text file. But when I do, it exports the whole table data instead of just the searched data. This is what i have tried:
DefaultTableModel Model = (DefaultTableModel)table.getModel();
TableRowSorter<DefaultTableModel> tr = new TableRowSorter<DefaultTableModel>(Model);
table.setRowSorter(tr);
if(srchop.getSelectedItem().toString() == "Name Of Publication") {
tr.setRowFilter(RowFilter.regexFilter(nameOfPub.getText().trim().toLowerCase()));
}else if() {
//code for search through other jtextfields
}else{}
table.setAutoCreateRowSorter(true);
table.setRowSorter(tr);
JFileChooser fileChooser = new JFileChooser();
fileChooser.setDialogTitle("Export the data to");
fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("XML Documents","xml"));
fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("Text Files","txt"));
fileChooser.setAcceptAllFileFilterUsed(true);
int userSelection = fileChooser.showSaveDialog(this);
if(userSelection == JFileChooser.APPROVE_OPTION){
File fileToSave = fileChooser.getSelectedFile();
String ftsEx = fileToSave.getPath();
int index = ftsEx.lastIndexOf('.');
String ext = ftsEx.substring(index + 1);
try {
if(ext.equals("txt")) {
FileWriter fw = new FileWriter(fileToSave);
BufferedWriter bw = new BufferedWriter(fw);
for (int i = 0; i < model.getRowCount(); i++) {
for (int j = 0; j < model.getColumnCount(); j++) {
bw.write(model.getValueAt(i, j).toString()+" ");
}
bw.newLine();
}
JOptionPane.showMessageDialog(this, "EXPORT SUCCESSFUL","INFORMATION",JOptionPane.INFORMATION_MESSAGE);
bw.close();
fw.close();
}else if(ext.equals("xml")) {
////XML export code
}
Is there any way I can store the filtered data to some other jtable and then use that to print into the file. Or any other way it can be achieved?