Actually, my need is that I have a jtable with 38 columns and i want to call the selected Jtable columns for printing. Problem is not print function,but how can i mark the columns i want to print? Plz
Asked
Active
Viewed 2,800 times
1 Answers
2
To particular column in JTable you can to pass String value "true"
for RowFilter for checked JCheckBox(es)
, and String value "false"
for un_checked JCheckBox(es)
, then print JTable and after printing to the printer to clear String to ""
in the RowFilter
or simpler could be to use Boolean value directly
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import javax.swing.*;
import javax.swing.RowFilter;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
public class JTableFilterDemo {
private static TableRowSorter<TableModel> sorter;
public static void main(String[] args) {
Object[][] data = {{"A", 5, true}, {"B", 2, false}, {"C", 4, false}, {"D", 8, true}};
String columnNames[] = {"Item", "Value", "Boolean"};
TableModel model = new DefaultTableModel(data, columnNames) {
private static final long serialVersionUID = 1L;
@Override
public Class<?> getColumnClass(int column) {
return getValueAt(0, column).getClass();
}
};
JTable table = new JTable(model);
table.setPreferredScrollableViewportSize(table.getPreferredSize());
RowFilter<Object, Object> filter = new RowFilter<Object, Object>() {
public boolean include(Entry entry) {
Boolean bol = (Boolean) entry.getValue(2);
return bol.booleanValue() == true;
}
};
sorter = new TableRowSorter<TableModel>(model);
sorter.setRowFilter(filter);
table.setRowSorter(sorter);
JScrollPane scrollPane = new JScrollPane(table);
JFrame frame = new JFrame("Filtering Table");
frame.add(new JButton(new AbstractAction("Toggle filter") {
private static final long serialVersionUID = 1L;
private RowFilter<TableModel, Object> filter = new RowFilter<TableModel, Object>() {
@Override
public boolean include(javax.swing.RowFilter.Entry<? extends TableModel, ? extends Object> entry) {
Boolean bol = (Boolean) entry.getValue(2);
return bol.booleanValue() == false;
}
};
@Override
public void actionPerformed(ActionEvent e) {
if (sorter.getRowFilter() != null) {
sorter.setRowFilter(null);
} else {
sorter.setRowFilter(filter);
}
}
}), BorderLayout.SOUTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(scrollPane);
frame.pack();
frame.setVisible(true);
}
}

mKorbel
- 109,525
- 20
- 134
- 319
-
+1 for using the model; see also this [Q&A](http://stackoverflow.com/q/7137786/230513). – trashgod May 31 '12 at 14:06
-
I'd say filtering the model, as you show, is most likely to produce a conveniently printable view. For larger selections, I _think_ `JTable#print()` will respect the filter. – trashgod May 31 '12 at 18:15