Tabelle filtern und Zeilen löschen. Zeilen auch in ursprünglicher Tabelle löschen

Mmmh, erstmal danke.
Ich versteh zwar im Moment noch net so ganz was du meinst, bzw., wie ich das umsetzen soll/kann
Aber ich versuch mich mal da reinzuhängen.
Falls du noch irgendwelche Tipps hast, kann sie gerne posten ;-)
 
Morgen,
also um ganz ehrlich zu sein, versteh ich das alles nicht wirklich.
Hast du zufällig irgendwelche Codeschnipsel oder so?
Irgendetwas, so dass ich vielleicht irgendnen Ansatz habe

Im Voraus schon mal besten Dank.
 
Moin,
sorry, verständlichen Codeschnippsel nicht, wäre aus einem etwas größeren Projekt. Und "mal eben" nebenbei ein Beispiel zimmern, dazu fehlt mir etwas die Zeit. Ist auch nicht in einer Viertelstunde erledigt...
Allerdings geht das Gerücht um, dass Tom öfter Langeweile hat und Beispielprogramme bastelt. ;)
 
Mmh, ok. kein Problem.
Wusste nicht, dass das doch ein wenig größerer Aufwand ist.
Trotzdem danke.

Dann kuck ich halt mal, vielleicht hat Tom ja tatsächlich mal Zeit um so ein Beispielprogramm zu schreiben.
 
Hallo!

Schau mal hier:
Code:
 /**
  * 
  */
 package de.tutorials;
 
 import java.awt.BorderLayout;
 import java.awt.Point;
 import java.awt.event.ActionEvent;
 import java.awt.event.ActionListener;
 import java.awt.event.KeyAdapter;
 import java.awt.event.KeyEvent;
 import java.awt.event.MouseAdapter;
 import java.awt.event.MouseEvent;
 import java.lang.reflect.Method;
 
 import javax.swing.JComboBox;
 import javax.swing.JFrame;
 import javax.swing.JMenuItem;
 import javax.swing.JPopupMenu;
 import javax.swing.JScrollPane;
 import javax.swing.JTable;
 import javax.swing.JTextField;
 import javax.swing.SwingUtilities;
 import javax.swing.table.AbstractTableModel;
 import javax.swing.table.DefaultTableModel;
 import javax.swing.table.TableModel;
 
 /**
  * @author Tom
  * 
  */
 public class FilteredJTableExample extends JFrame {
 
 	FilterableJTable table;
 	JTextField txtFilter;
 	JComboBox cboSelectFilterColumn;
 	final static String DEFAULT_FILTER = "^#.*";
 	JPopupMenu popupMenu;
 
 	public FilteredJTableExample() {
 		super("FilteredJTableExample");
 		setDefaultCloseOperation(EXIT_ON_CLOSE);
 
 		popupMenu = createPopupMenu();
 
 		table = new FilterableJTable(createFilterAbleTableModel());
 		table.addMouseListener(new MouseAdapter() {
 			public void mousePressed(MouseEvent e) {
 				if (SwingUtilities.isRightMouseButton(e)) {
 					Point point = e.getPoint();
 		    		popupMenu.show(table, point.x, point.y);
 				}
 			}
 		});
 
 		txtFilter = new JTextField(20);
 
 		txtFilter.addKeyListener(new KeyAdapter() {
 			public void keyReleased(KeyEvent e) {
 				table.setFilter(DEFAULT_FILTER
 		    			.replace("#", txtFilter.getText()));
 				table.updateUI();
 			}
 		});
 
 		cboSelectFilterColumn = new JComboBox(createHeaderNames());
 		cboSelectFilterColumn.addActionListener(new ActionListener() {
 			public void actionPerformed(ActionEvent e) {
 		        table.setFilterColumn(cboSelectFilterColumn.getSelectedIndex());
 			}
 		});
 
 		JScrollPane scrollPane = new JScrollPane(table);
 
 		add(cboSelectFilterColumn, BorderLayout.WEST);
 		add(txtFilter, BorderLayout.EAST);
 		add(scrollPane, BorderLayout.SOUTH);
 
 		pack();
 		setVisible(true);
 	}
 
 	JPopupMenu createPopupMenu() {
 		JPopupMenu menu = new JPopupMenu();
 		JMenuItem deleteItem = new JMenuItem("delete");
 		deleteItem.addActionListener(new ActionListener() {
 			public void actionPerformed(ActionEvent e) {
 				int selectedRow = table.getSelectedRow();
 		    	System.out.println("removeRow @idx: " + selectedRow);
 				table.deleteRow(selectedRow);
 			}
 		});
 		menu.add(deleteItem);
 		return menu;
 	}
 
 	private TableModel createFilterAbleTableModel() {
 		return new DefaultTableModel(createRowData(), createHeaderNames());
 	}
 
 	private Object[][] createRowData() {
 		return new Object[][]{{"aaa", "121"}, {"aab", "111"}, {"abc", "123"},
 				{"xabc", "4123"}};
 	}
 
 	private Object[] createHeaderNames() {
 		return new Object[]{"A", "B"};
 	}
 
 	/**
 	 * @param args
 	 */
 	public static void main(String[] args) {
 		new FilteredJTableExample();
 	}
 
 	static class FilterableJTable extends JTable {
 		String filter;
 		FilterableTableModel filterableTableModel;
 		int filterColumn;
 
 		int currentFilterMatches;
 		int[] currentFilterMapping;
 
 		public FilterableJTable(TableModel model) {
 			super(model);
 			filterableTableModel = new FilterableTableModel(model);
 		}
 
 		public void deleteRow(int selectedRow) {
 			TableModel model = getModel();
 			try {
 		    	Method deleteRowMethod = model.getClass().getDeclaredMethod(
 		    			"removeRow", new Class[]{int.class});
 				if (deleteRowMethod != null) {
 		    		deleteRowMethod.invoke(model, new Object[]{Integer
 		    		    	.valueOf(selectedRow)});
 				}
 			} catch (Exception e) {
 				throw new UnsupportedOperationException(e);
 			}
 		}
 
 		public int getFilterColumn() {
 			return filterColumn;
 		}
 
 		public void setFilterColumn(int currentFilterColumn) {
 			this.filterColumn = currentFilterColumn;
 		}
 
 		public int[] getCurrentFilterMapping() {
 			return currentFilterMapping;
 		}
 
 		public void setCurrentFilterMapping(int[] currentFilterMapping) {
 			this.currentFilterMapping = currentFilterMapping;
 		}
 
 		public int getCurrentFilterMatches() {
 			return currentFilterMatches;
 		}
 
 		public void setCurrentFilterMatches(int currentFilterMatches) {
 			this.currentFilterMatches = currentFilterMatches;
 		}
 
 		public String getFilter() {
 			return filter;
 		}
 
 		public void setFilter(String filter) {
 			this.filter = filter;
 		}
 
 		public FilterableTableModel getFilterableTableModel() {
 			return filterableTableModel;
 		}
 
 		public void setFilterableTableModel(
 				FilterableTableModel filterableTableModel) {
 			this.filterableTableModel = filterableTableModel;
 		}
 
 		private void doFilter() {
 			currentFilterMatches = 0;
 			TableModel model = super.getModel();
 			int rowCount = model.getRowCount();
 			int[] tmpMapping = new int[rowCount];
 
 			for (int i = 0, j = 0; i < rowCount; i++) {
 		    	if (model.getValueAt(i, filterColumn).toString().matches(
 		    			this.filter)) {
 					currentFilterMatches++;
 					tmpMapping[j++] = i;
 				}
 			}
 
 			currentFilterMapping = new int[currentFilterMatches];
 			System.arraycopy(tmpMapping, 0, currentFilterMapping, 0,
 					currentFilterMatches);
 			this.filterableTableModel.setFilterMapping(currentFilterMapping);
 		}
 
 		public TableModel getModel() {
 			if (filter == null || filter.equals("")) {
 				return super.getModel();
 			} else {
 				doFilter();
 				return filterableTableModel;
 			}
 		}
 	}
 
 	static class FilterableTableModel extends AbstractTableModel {
 
 		TableModel delegateTableModel;
 		int[] filterMapping;
 
 		public FilterableTableModel(TableModel delegateTableModel) {
 			this.delegateTableModel = delegateTableModel;
 		}
 
 		public int getRowCount() {
 			return this.filterMapping != null ? this.filterMapping.length : 0;
 		}
 
 		public int getColumnCount() {
 			return delegateTableModel.getColumnCount();
 		}
 
 		public Object getValueAt(int rowIndex, int columnIndex) {
 			return delegateTableModel.getValueAt(this.filterMapping[rowIndex],
 					columnIndex);
 		}
 
 		public int[] getFilterMapping() {
 			return filterMapping;
 		}
 
 		public void setFilterMapping(int[] filterMapping) {
 			this.filterMapping = filterMapping;
 		}
 
 		public TableModel getDelegateTableModel() {
 			return delegateTableModel;
 		}
 
 		public void setDelegateTableModel(TableModel delegate) {
 			this.delegateTableModel = delegate;
 		}
 
 		public void removeRow(int idx) {
 			if (delegateTableModel instanceof DefaultTableModel) {
 				((DefaultTableModel) delegateTableModel)
 		    		    .removeRow(filterMapping[idx]);
 
 			} else {
 				throw new UnsupportedOperationException();
 			}
 		}
 	}
 }

Gruss Tom
 
Hallo!

hier mal noch mal schnell eine refactorierte Version...
Code:
/**
  * 
  */
 package de.tutorials;
 
 import java.awt.BorderLayout;
 import java.awt.Point;
 import java.awt.event.ActionEvent;
 import java.awt.event.ActionListener;
 import java.awt.event.KeyAdapter;
 import java.awt.event.KeyEvent;
 import java.awt.event.MouseAdapter;
 import java.awt.event.MouseEvent;
 import java.lang.reflect.Method;
 
 import javax.swing.JComboBox;
 import javax.swing.JFrame;
 import javax.swing.JMenuItem;
 import javax.swing.JOptionPane;
 import javax.swing.JPopupMenu;
 import javax.swing.JScrollPane;
 import javax.swing.JTable;
 import javax.swing.JTextField;
 import javax.swing.SwingUtilities;
 import javax.swing.table.AbstractTableModel;
 import javax.swing.table.DefaultTableModel;
 import javax.swing.table.TableModel;
 
 /**
  * @author Tom
  * 
  */
 public class FilteredJTableExample extends JFrame {
 
 	FilterableJTable table;
 	JTextField txtFilter;
 	JComboBox cboSelectFilterColumn;
 	final static String DEFAULT_FILTER = "^#.*";
 	JPopupMenu popupMenu;
 
 	public FilteredJTableExample() {
 		super("FilteredJTableExample");
 		setDefaultCloseOperation(EXIT_ON_CLOSE);
 
 		popupMenu = createPopupMenu();
 
 		table = new FilterableJTable(createFilterableTableModel());
 		table.addMouseListener(new MouseAdapter() {
 			public void mousePressed(MouseEvent e) {
 				if (SwingUtilities.isRightMouseButton(e)) {
 					Point point = e.getPoint();
 		    		popupMenu.show(table, point.x, point.y);
 				}
 			}
 		});
 
 		txtFilter = new JTextField(20);
 
 		txtFilter.addKeyListener(new KeyAdapter() {
 			public void keyReleased(KeyEvent e) {
 				table.setFilter(DEFAULT_FILTER
 		    			.replace("#", txtFilter.getText()));
 				table.updateUI();
 			}
 		});
 
 		cboSelectFilterColumn = new JComboBox(createHeaderNames());
 		cboSelectFilterColumn.addActionListener(new ActionListener() {
 			public void actionPerformed(ActionEvent e) {
 		        table.setFilterColumn(cboSelectFilterColumn.getSelectedIndex());
 			}
 		});
 
 		JScrollPane scrollPane = new JScrollPane(table);
 
 		add(cboSelectFilterColumn, BorderLayout.WEST);
 		add(txtFilter, BorderLayout.EAST);
 		add(scrollPane, BorderLayout.SOUTH);
 
 		pack();
 		setVisible(true);
 	}
 
 	JPopupMenu createPopupMenu() {
 		JPopupMenu menu = new JPopupMenu();
 		JMenuItem deleteItem = new JMenuItem("delete");
 		deleteItem.addActionListener(new ActionListener() {
 			public void actionPerformed(ActionEvent e) {
 				int selectedRow = table.getSelectedRow();
 				if (selectedRow == -1) {
 		    	    JOptionPane.showMessageDialog(FilteredJTableExample.this,
 		    		    	"No row selected!", "Error",
 		    		    	JOptionPane.ERROR_MESSAGE);
 					return;
 				}
 		    	System.out.println("removeRow @idx: " + selectedRow);
 				table.deleteRow(selectedRow);
 				table.updateUI();
 			}
 		});
 		menu.add(deleteItem);
 		return menu;
 	}
 
 	private TableModel createFilterableTableModel() {
 		return new DefaultTableModel(createRowData(), createHeaderNames());
 	}
 
 	private Object[][] createRowData() {
 		return new Object[][]{{"aaa", "121"}, {"aab", "111"}, {"abc", "123"},
 				{"xabc", "4123"}};
 	}
 
 	private Object[] createHeaderNames() {
 		return new Object[]{"A", "B"};
 	}
 
 	/**
 	 * @param args
 	 */
 	public static void main(String[] args) {
 		new FilteredJTableExample();
 	}
 
 	static class FilterableJTable extends JTable {
 
 		public FilterableJTable(TableModel model) {
 			super(new FilterableTableModel(model));
 		}
 
 		public void deleteRow(int selectedRow) {
 			((FilterableTableModel) this.getModel()).deleteRow(selectedRow);
 		}
 
 		public void setFilterColumn(int filterColumn) {
 			((FilterableTableModel) this.getModel())
 					.setFilterColumn(filterColumn);
 		}
 
 		public int getFilterColumn() {
 			return ((FilterableTableModel) this.getModel()).getFilterColumn();
 		}
 
 		public void setFilter(String filter) {
 			((FilterableTableModel) this.getModel()).setFilter(filter);
 		}
 
 		public String getFilter() {
 			return ((FilterableTableModel) this.getModel()).getFilter();
 		}
 
 	}
 
 	static class FilterableTableModel extends AbstractTableModel {
 
 		TableModel delegateTableModel;
 		int[] filterMapping;
 		String filter;
 		int filterColumn;
 		int filterMatchCount;
 
 		public FilterableTableModel(TableModel delegateTableModel) {
 			this.delegateTableModel = delegateTableModel;
 		}
 
 		public int getRowCount() {
 			if (isFilterEnabled()) {
 				doFilter();
 			}
 
 			return this.filterMapping != null
 					? this.filterMapping.length
 		    		: this.delegateTableModel.getRowCount();
 		}
 
 		public int getColumnCount() {
 			return delegateTableModel.getColumnCount();
 		}
 
 		public Object getValueAt(int rowIndex, int columnIndex) {
 			int actualRowIndex = rowIndex;
 			if (isFilterEnabled()) {
 				actualRowIndex = this.filterMapping[rowIndex];
 			}
 			return delegateTableModel.getValueAt(actualRowIndex, columnIndex);
 		}
 
 		public int[] getFilterMapping() {
 			return filterMapping;
 		}
 
 		public void setFilterMapping(int[] filterMapping) {
 			this.filterMapping = filterMapping;
 		}
 
 		public TableModel getDelegateTableModel() {
 			return delegateTableModel;
 		}
 
 		public void setDelegateTableModel(TableModel delegate) {
 			this.delegateTableModel = delegate;
 		}
 
 		public void deleteRow(int selectedRow) {
 			try {
 		    	Method deleteRowMethod = delegateTableModel.getClass()
 		    		    .getDeclaredMethod("removeRow", new Class[]{int.class});
 				if (deleteRowMethod != null) {
 		    	    deleteRowMethod.invoke(delegateTableModel,
 		    		    	new Object[]{Integer.valueOf(selectedRow)});
 				}
 			} catch (Exception e) {
 				throw new UnsupportedOperationException(e);
 			}
 		}
 
 		private void doFilter() {
 			filterMatchCount = 0;
 			int rowCount = delegateTableModel.getRowCount();
 			int[] tmpMapping = new int[rowCount];
 
 			for (int i = 0; i < rowCount; i++) {
 		    	if (delegateTableModel.getValueAt(i, filterColumn).toString()
 		    		    .matches(this.filter)) {
 		    		tmpMapping[filterMatchCount++] = i;
 				}
 			}
 
 			int[] currentFilterMapping = new int[filterMatchCount];
 			System.arraycopy(tmpMapping, 0, currentFilterMapping, 0,
 					filterMatchCount);
 			setFilterMapping(currentFilterMapping);
 		}
 
 		public int getFilterMatchCount() {
 			return filterMatchCount;
 		}
 
 		public void setFilterMatchCount(int filterMatches) {
 			this.filterMatchCount = filterMatches;
 		}
 
 		public String getFilter() {
 			return filter;
 		}
 
 		public void setFilter(String filter) {
 			this.filter = filter;
 		}
 
 		boolean isFilterEnabled() {
 			return getFilter() != null && !"".equals(getFilter());
 		}
 
 		public int getFilterColumn() {
 			return filterColumn;
 		}
 
 		public void setFilterColumn(int filterColumn) {
 			this.filterColumn = filterColumn;
 		}
 	}
 }

Gruss Tom
 
Hi Tom,

vielen, vielen Dank für den Code. Ganz großes Tennis.
Er bringt bei mir zwar momentan noch ein paar Fehlermeldungen. Aber ich hoffe, dass ich das behoben bring.
Und dann kuck ich mal, ob es das ist was ich gesucht hab ;-)

Gruß Diable
 
Irgendwie krieg ich da ein paar Sachen net so hin, wie ich will.
Also erstmal danke Tom für den Code. Genau so, will ich das auch hinbekommen.
Nur leider, bekomm ich deine Klasse FilterableTableModel und meine Klasse TableRowsTableModel nicht vereint, bzw. nicht so vereint, dass mein Prog läuft.

Code:
public class TableRowsTableModel extends DefaultTableModel {
	private String[] columnNames = {"Nr",
									"Anfrageart",
									"Teilnehmernr",
									"Name",
									"Vorname",
									"Strasse",
									"Ort",
									"kASpalte"};
	
	private Class[] classTypes = {Integer.class, //Spalte 0: Nr
								  String.class,  //Spalte 1: Anfrageart
								  String.class,	 //Spalte 2: Teilnehmernummer
								  String.class,  //Spalte 3: Name
								  String.class,  //Spalte 4: Vorname
								  String.class,  //Spalte 5: Strasse
								  String.class,  //Spalte 6: Ort
								  String.class,  //Spalte 7: Spalte
								  };
	
		
	TableRowsTableModel() {
		super();
	}

	public int getColumnCount() {
		return columnNames.length;
	}
	
	public String getColumnName(int col) {
		return columnNames[col];
	}
	
	public Class getColumnClass (int columnIndex) {
		return classTypes[columnIndex];
	}
	
	public int getRowCount() {
		return getRows().size();
	}
	
	public Object getValueAt(int rowIndex, int columnIndex) {	
		Object objRet = null;
		try {			
			objRet = ((TableRows) getRows().get(rowIndex)).getValueAt(columnIndex);
		} catch (Exception e){
			
		}
		return objRet;
	}
	
	private TableRows getRow(int row) {
		return (TableRows) getRows().get(row);
	}
	
	private List rows;
	
	public List getRows() {
		if (rows == null) {
			rows = new ArrayList();
		}		
		return rows;
	}
	
	public void addRow(TableRows newRow) {
		getRows().add(newRow);
		fireTableDataChanged();
	}
	
	public void deleteRow(int delRow) {
		getRows().remove(delRow);
		fireTableDataChanged();
	}
}
 
Also falls mir irgendjemand von euch nochmal helfen könnte, wär ich euch dankbar.
Wie gesagt, muss ich die Klasse FilterableTableModel und "meine" Klasse TableRowsTableModel zusammenfügen? und wenn ja wie?

Wenn ich das richtig sehe, kann ich mit der Klasse FilterableTableModel alleine ja keine Daten einlesen, oder

Also, falls mir irgendjemand nochmal Tipps geben könnte, wär das echt klasse.
Bin grad total am Verzweifeln.
 
Hallo!

Es ist doch kein Problem die Einfüg-Fähigkeit hinzuzufügen... das zugrundeliegende TableModel muss das nur unterstützen... sortieren ist auch nicht viel schwerer...
Code:
/**
 * 
 */
package de.tutorials;

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.lang.reflect.Method;
import java.util.regex.PatternSyntaxException;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;

/**
 * @author Tom
 * 
 */
public class FilteredJTableExample extends JFrame {

	FilterableJTable table;
	JTextField txtFilter, txtA, txtB;
	JButton btnAddRow;
	JComboBox cboSelectFilterColumn;
	final static String DEFAULT_FILTER = "^#.*";
	JPopupMenu popupMenu;

	public FilteredJTableExample() {
		super("FilteredJTableExample");
		setDefaultCloseOperation(EXIT_ON_CLOSE);

		popupMenu = createPopupMenu();

		table = new FilterableJTable(createFilterableTableModel());
		table.addMouseListener(new MouseAdapter() {
			public void mousePressed(MouseEvent e) {
				if (SwingUtilities.isRightMouseButton(e)) {
					Point point = e.getPoint();
					popupMenu.show(table, point.x, point.y);
				}
			}
		});

		txtFilter = new JTextField(20);

		txtFilter.addKeyListener(new KeyAdapter() {
			public void keyReleased(KeyEvent e) {
				table.setFilter(DEFAULT_FILTER
						.replace("#", txtFilter.getText()));
				table.updateUI();
			}
		});

		cboSelectFilterColumn = new JComboBox(createHeaderNames());
		cboSelectFilterColumn.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				table.setFilterColumn(cboSelectFilterColumn.getSelectedIndex());
			}
		});

		JScrollPane scrollPane = new JScrollPane(table);

		JPanel addRowPanel = new JPanel(new GridLayout(1, 5));
		txtA = new JTextField(5);
		txtB = new JTextField(5);
		btnAddRow = new JButton("add");
		btnAddRow.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				String strA = txtA.getText();
				String strB = txtB.getText();
				if (!"".equals(strA) && !"".equals(strB)) {
					table.addRow(new Object[] { strA, strB });
					table.updateUI();
					txtA.setText("");
					txtB.setText("");
				}
			}
		});
		addRowPanel.add(new JLabel("A:"));
		addRowPanel.add(txtA);
		addRowPanel.add(new JLabel("B:"));
		addRowPanel.add(txtB);
		addRowPanel.add(btnAddRow);

		add(addRowPanel, BorderLayout.NORTH);
		add(cboSelectFilterColumn, BorderLayout.WEST);
		add(txtFilter, BorderLayout.EAST);
		add(scrollPane, BorderLayout.SOUTH);

		pack();
		setVisible(true);
	}

	JPopupMenu createPopupMenu() {
		JPopupMenu menu = new JPopupMenu();
		JMenuItem deleteItem = new JMenuItem("delete");
		deleteItem.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				int selectedRow = table.getSelectedRow();
				if (selectedRow == -1) {
					JOptionPane.showMessageDialog(FilteredJTableExample.this,
							"No row selected!", "Error",
							JOptionPane.ERROR_MESSAGE);
					return;
				}
				System.out.println("removeRow @idx: " + selectedRow);
				table.deleteRow(selectedRow);
				table.updateUI();
			}
		});
		menu.add(deleteItem);
		return menu;
	}

	private TableModel createFilterableTableModel() {
		return new DefaultTableModel(createRowData(), createHeaderNames());
	}

	private Object[][] createRowData() {
		return new Object[][] { { "aaa", "121" }, { "aab", "111" },
				{ "abc", "123" }, { "xabc", "4123" } };
	}

	private Object[] createHeaderNames() {
		return new Object[] { "A", "B" };
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		new FilteredJTableExample();
	}

	static class FilterableJTable extends JTable {

		public FilterableJTable(TableModel model) {
			super(new FilterableTableModel(model));
		}

		public void deleteRow(int selectedRow) {
			((FilterableTableModel) this.getModel()).deleteRow(selectedRow);
		}

		public void setFilterColumn(int filterColumn) {
			((FilterableTableModel) this.getModel())
					.setFilterColumn(filterColumn);
		}

		public int getFilterColumn() {
			return ((FilterableTableModel) this.getModel()).getFilterColumn();
		}

		public void setFilter(String filter) {
			((FilterableTableModel) this.getModel()).setFilter(filter);
		}

		public String getFilter() {
			return ((FilterableTableModel) this.getModel()).getFilter();
		}

		public void addRow(Object[] rowColumns) {
			((FilterableTableModel) this.getModel()).addRow(rowColumns);
		}
	}

	static class FilterableTableModel extends AbstractTableModel {

		TableModel delegateTableModel;
		int[] filterMapping;
		String filter;
		int filterColumn;
		int filterMatchCount;

		public FilterableTableModel(TableModel delegateTableModel) {
			this.delegateTableModel = delegateTableModel;
		}

		public void addRow(Object[] rowColumns) {
			try {
				Method addRowMethod = delegateTableModel.getClass()
						.getDeclaredMethod("addRow",
								new Class[] { Object[].class });
				if (addRowMethod != null) {
					addRowMethod.invoke(delegateTableModel,
							new Object[] { rowColumns });
				} else {
					throw new UnsupportedOperationException(
							"Adding Rows is not supported by: "
									+ delegateTableModel.getClass());
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		public void deleteRow(int selectedRow) {
			try {
				Method deleteRowMethod = delegateTableModel.getClass()
						.getDeclaredMethod("removeRow",
								new Class[] { int.class });
				if (deleteRowMethod != null) {
					deleteRowMethod.invoke(delegateTableModel,
							new Object[] { Integer.valueOf(selectedRow) });
				} else {
					throw new UnsupportedOperationException(
							"Deleting Rows is not supported by: "
									+ delegateTableModel.getClass());
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		public int getRowCount() {
			if (isFilterEnabled()) {
				doFilter();
			}

			return this.filterMapping != null ? this.filterMapping.length
					: this.delegateTableModel.getRowCount();
		}

		public int getColumnCount() {
			return delegateTableModel.getColumnCount();
		}

		public Object getValueAt(int rowIndex, int columnIndex) {
			int actualRowIndex = rowIndex;
			if (isFilterEnabled()) {
				actualRowIndex = this.filterMapping[rowIndex];
			}
			return delegateTableModel.getValueAt(actualRowIndex, columnIndex);
		}

		public int[] getFilterMapping() {
			return filterMapping;
		}

		public void setFilterMapping(int[] filterMapping) {
			this.filterMapping = filterMapping;
		}

		public TableModel getDelegateTableModel() {
			return delegateTableModel;
		}

		public void setDelegateTableModel(TableModel delegate) {
			this.delegateTableModel = delegate;
		}

		private void doFilter() {
			filterMatchCount = 0;
			int rowCount = delegateTableModel.getRowCount();
			int[] tmpMapping = new int[rowCount];

			for (int i = 0; i < rowCount; i++) {
				try {
					if (delegateTableModel.getValueAt(i, filterColumn)
							.toString().matches(this.filter)) {
						tmpMapping[filterMatchCount++] = i;
					}
				} catch (PatternSyntaxException patternSyntaxException) {
					filterMatchCount = 0;
					return;
				}
			}

			int[] currentFilterMapping = new int[filterMatchCount];
			System.arraycopy(tmpMapping, 0, currentFilterMapping, 0,
					filterMatchCount);
			setFilterMapping(currentFilterMapping);
		}

		public int getFilterMatchCount() {
			return filterMatchCount;
		}

		public void setFilterMatchCount(int filterMatches) {
			this.filterMatchCount = filterMatches;
		}

		public String getFilter() {
			return filter;
		}

		public void setFilter(String filter) {
			this.filter = filter;
		}

		boolean isFilterEnabled() {
			return getFilter() != null && !"".equals(getFilter());
		}

		public int getFilterColumn() {
			return filterColumn;
		}

		public void setFilterColumn(int filterColumn) {
			this.filterColumn = filterColumn;
		}
	}
}

Gruss Tom
 
Zurück