JTable mit ComboBox als Filter

hesk

Erfahrenes Mitglied
JTable mit ComboBox im Header als Filter [Programm enthalten]

Hallo!

Was ich gerne hätte ist eine JTable die in der ersten Reihe die Column-Namen hat,
in der zweiten Reihe eine ComboBox mit Auswahlkriterien.
Anhand der Auswahl in der ComboBox soll dann die Table gefiltert werden.

Ich habe im Internet ein Bsp gefunden wie man so eine ComboBox macht.
Jetzt habe ich versucht einen Filter dazu zu bauen, aber es funktioniert nicht.

Kann sich vielleicht jemand den Code anschauen und mir weiter helfen?
Danke!

Code:
package swing;

/* (@)JTableHeaderComboBoxDemo.java */

/*
 * Copyright 2009 Sebastian Haufe Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
 * file except in compliance with the License. You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied. See the License for the specific language governing permissions and limitations under the
 * License.
 */

import java.awt.Component;
import java.awt.Container;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Insets;
import java.awt.LayoutManager;
import java.awt.LayoutManager2;
import java.awt.Rectangle;
import java.util.HashMap;
import java.util.Map;

import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.RowFilter;
import javax.swing.SwingConstants;
import javax.swing.WindowConstants;
import javax.swing.event.TableColumnModelEvent;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;

import swing.TableFilterDemo.MyTableModel;

/**
 * A table header with one combo box for each column.
 * 
 * @author Sebastian Haufe
 */
public class JTableHeaderComboBoxDemo
{

    private TableRowSorter<TableModel> sorter;

    private void newFilter()
    {
        RowFilter<TableModel, Object> rf = null;
        // If current expression doesn't parse, don't update.
        try
        {
            rf = RowFilter.regexFilter( "Kathy" );
        }
        catch ( java.util.regex.PatternSyntaxException e )
        {
            return;
        }
        sorter.setRowFilter( rf );
    }

    /**
     * Extended table header, adding the preferred height of the layout to its preferred height and revalidates when the
     * dragged column is released.
     */
    private static class JXTableHeader extends JTableHeader
    {

        JXTableHeader( TableColumnModel cm )
        {
            super( cm );
        }

        @Override
        public Dimension getPreferredSize()
        {
            final Dimension size = super.getPreferredSize();
            final LayoutManager layout = getLayout();
            if ( layout != null )
            {
                size.height += layout.preferredLayoutSize( this ).height;
            }
            return size;
        }

        @Override
        public void columnMoved( TableColumnModelEvent e )
        {
            super.columnMoved( e );
            if ( getDraggedColumn() != null )
            {
                revalidate();
                repaint();
            }
        }

        @Override
        public void setDraggedColumn( TableColumn column )
        {
            super.setDraggedColumn( column );
            if ( column == null )
            {
                revalidate();
                repaint();
            }
        }
    }

    /**
     * Layout for table header. Manages components on the table header, using the component index as index in the table
     * model! Calculates the preferred size with a width of zero and a height of the maximum preferred height of all
     * components. Lays out the components in their header rectangle, using an additional margin.
     */
    private static final class TableHeaderSouthLayout
                                                     implements LayoutManager2, java.io.Serializable
    {

        private Insets margin = new Insets( 1, 1, 1, 1 );
        private final Map<Component, Integer> components =
                new HashMap<Component, Integer>();

        /**
         * Get the cell margin.
         * 
         * @return the cell margin
         */
        public Insets getMargin()
        {
            return margin;
        }

        /**
         * Set the cell margin.
         * 
         * @param m
         *            the margin
         * @throws IllegalArgumentException
         *             if {@code margin} is {@code null}
         */
        public void setMargin( Insets m )
        {
            if ( m == null )
            {
                throw new IllegalArgumentException( //
                                                    "margin not allowed null" ); //$NON-NLS-1$
            }
            this.margin = new Insets( m.top, m.left, m.bottom, m.right );
        }

        public void layoutContainer( Container parent )
        {
            final JTableHeader th = ( (JTableHeader) parent );
            final JTable table = th.getTable();
            final int componentCount = th.getComponentCount();
            for ( int i = 0; i < componentCount; i++ )
            {
                final Component comp = th.getComponent( i );
                final Integer columnIndexObj = components.get( comp );
                final int colIndex;
                final int viewIndex;
                if ( table == null
                     || columnIndexObj == null
                     || ( colIndex = columnIndexObj.intValue() ) < 0
                     || ( viewIndex = table.convertColumnIndexToView( colIndex ) ) < 0
                     || viewIndex >= table.getColumnCount() )
                {
                    comp.setBounds( 0, 0, 0, 0 );
                }
                else
                {
                    final Rectangle rect = th.getHeaderRect( viewIndex );
                    final TableColumn draggedColumn = th.getDraggedColumn();
                    if ( draggedColumn != null
                         && draggedColumn.getModelIndex() == colIndex )
                    {
                        rect.x += th.getDraggedDistance();
                        th.setComponentZOrder( comp, 0 );
                    }
                    rect.x += margin.left;
                    rect.y += margin.top;
                    rect.width -= margin.left + margin.right;
                    rect.height -= margin.top + margin.bottom;
                    final Dimension size = comp.getPreferredSize();
                    if ( rect.height > size.height )
                    {
                        rect.y += rect.height - size.height;
                        rect.height = size.height;
                    }
                    comp.setBounds( rect );
                }
            }
        }

        public Dimension preferredLayoutSize( Container parent )
        {
            final JTableHeader th = ( (JTableHeader) parent );
            final JTable table = th.getTable();
            final int componentCount = th.getComponentCount();
            int h = 0;
            for ( int i = 0; i < componentCount; i++ )
            {
                final Component comp = th.getComponent( i );
                final Integer columnIndexObj = components.get( comp );
                final int colIndex;
                final int viewIndex;
                if ( table != null
                     && columnIndexObj != null
                     && ( colIndex = columnIndexObj.intValue() ) >= 0
                     && ( viewIndex = table.convertColumnIndexToView( colIndex ) ) >= 0
                     && viewIndex < table.getColumnCount() )
                {
                    h = Math.max( h, comp.getPreferredSize().height );
                }
            }
            return new Dimension( 0, margin.top + margin.bottom + h );
        }

        public Dimension minimumLayoutSize( Container parent )
        {
            return new Dimension();
        }

        public Dimension maximumLayoutSize( Container target )
        {
            return new Dimension();
        }

        public void removeLayoutComponent( Component comp )
        {
            components.remove( comp );
        }

        public void addLayoutComponent( Component comp, Object constraints )
        {
            if ( !( constraints instanceof Integer ) )
            {
                throw new IllegalArgumentException( //
                                                    "Wrong type: Integer expected" ); //$NON-NLS-1$
            }
            components.put( comp, (Integer) constraints );
        }

        public void addLayoutComponent( String name, Component comp )
        {
        }

        public float getLayoutAlignmentX( Container target )
        {
            return 0.5f;
        }

        public float getLayoutAlignmentY( Container target )
        {
            return 0.5f;
        }

        public void invalidateLayout( Container target )
        {
        }
    }
    
    private void initGuid()
    {
        String[] columnNames = { "First Name",
                                 "Last Name",
                                 "Sport",
                                 "# of Years",
                                 "Vegetarian" };

         Object[][] data = {
                            { "Kathy", "Smith",
                             "Snowboarding", new Integer( 5 ), new Boolean( false ) },
                            { "John", "Doe",
                             "Rowing", new Integer( 3 ), new Boolean( true ) },
                            { "Sue", "Black",
                             "Knitting", new Integer( 2 ), new Boolean( false ) },
                            { "Jane", "White",
                             "Speed reading", new Integer( 20 ), new Boolean( true ) },
                            { "Joe", "Brown",
                             "Pool", new Integer( 10 ), new Boolean( false ) }
         };
         
         /* table without auto-added table header */
         JTable table = new JTable( data, columnNames );
         
         table.setRowSorter( sorter );
         sorter = new TableRowSorter<TableModel>( table.getModel() );
         newFilter();
         
         table.setTableHeader( new JXTableHeader( table.getColumnModel() ) );

         final JTableHeader th = table.getTableHeader();
         final TableCellRenderer defaultRenderer = th.getDefaultRenderer();
         if ( defaultRenderer instanceof JLabel )
         {
             ( (JLabel) defaultRenderer ).setVerticalAlignment( SwingConstants.TOP );
         }
         th.setLayout( new TableHeaderSouthLayout() );

         th.add( createComboBox( new String[] { "Column A" } ), Integer.valueOf( 0 ) );
         th.add( createComboBox( new String[] { "Column B" } ), Integer.valueOf( 1 ) );
         th.add( createComboBox( new String[] { "Column C" } ), Integer.valueOf( 2 ) );
         th.add( createComboBox( new String[] { "Column D" } ), Integer.valueOf( 3 ) );
         th.add( createComboBox( new String[] { "true", "false" } ), Integer.valueOf( 4 ) );
         th.add( createComboBox( new String[] { "Column F" } ), Integer.valueOf( 5 ) );
         th.add( createComboBox( new String[] { "Column G" } ), Integer.valueOf( 6 ) );
         th.add( createComboBox( new String[] { "Column H" } ), Integer.valueOf( 7 ) );
         th.add( createComboBox( new String[] { "Column I" } ), Integer.valueOf( 8 ) );
         th.add( createComboBox( new String[] { "Column J" } ), Integer.valueOf( 9 ) );

         /* show the test frame */
         final JFrame f = new JFrame( //
                                      "Test Frame: JTableHeaderComboBoxDemo" ); //$NON-NLS-1$
         f.setContentPane( new JScrollPane( table ) );
         f.pack();
         f.setLocationRelativeTo( null );
         f.setDefaultCloseOperation( WindowConstants.EXIT_ON_CLOSE );
         f.setVisible( true );
    }

    /**
     * Test main method.
     * 
     * @param args
     *            ignored
     */
    public static void main( String[] args )
    {
        JTableHeaderComboBoxDemo test = new JTableHeaderComboBoxDemo();
        test.initGuid();
    }

    private static JComboBox createComboBox( final String[] data )
    {
        final JComboBox cb = new JComboBox( data );
        cb.setCursor( Cursor.getDefaultCursor() );
        return cb;
    }
}
 
Zuletzt bearbeitet:
Ich hab mal Testweise die newFilter() in initGui reingegeben.
Dort sollte eigentlich alles bis auf "Kathy" gefiltert werden.
Aber leider wird nichts gefiltert.
 
Hm, dummer Fehler.
Die beiden Zeilen mußten ausgetauscht werden... logisch:)

Code:
table.setRowSorter( sorter );
         sorter = new TableRowSorter<TableModel>( table.getModel() );

zu

Code:
sorter = new TableRowSorter<TableModel>( table.getModel() );
table.setRowSorter( sorter );
 
Wenn ich nun jeder ComboBox den selben ItemListener gebe:

Code:
final JComboBox cb = new JComboBox( data );
cb.setCursor( Cursor.getDefaultCursor() );
cb.addItemListener( this );

Kann ich dann in

Code:
public void itemStateChanged( ItemEvent evt )
    {
        if (evt.getStateChange() == ItemEvent.SELECTED )
        {

        }
    }

irgendwie rausfinden welche ComboBox gerade ausgewählt wurde?
Weil jede ComboBox ist für eine bestimmte Spalte.

Oder muss ich für jede ComboBox einen eigenen Listener machen?
 
Hm. Leider hab ich jetzt ein logisches Problem.

Jetzt bekomme ich zwar mit getSource die JComboBox, aber woher weiß ich jetzt an welcher Stelle die JComboBox steht?

Kann man beim erstellen der ComboBox quasi ein Property reingeben wo man sagt "du bist nr. 1" ?
 
Ich glaub mich gerade daran zu erinnern dass ich das schon mal in einem Thread hier gefragt habe:

Naja...hab auf jedenfall die Lösung schon gefunden.

Code:
cb.setName( "nr1" );

Im Listener:
Code:
((JComboBox)evt.getSource()).getName()
 
So... möchte nun auch das ganze Programm posten. Falls mal jemand das selbe Problem hat.

Eine JTable mit headers + JComboBox-Headers welche als DropDown-Items alle in er Spalte möglichen Werte hat.
Mittels der JComboBox kann dann gefiltert werden.

Der Code ist auf einem Beispielprogramm aus dem Internet aufgesetzt. Also nicht schön geschrieben, sondern für Testzwecke.

Code:
package swing;

/* (@)JTableHeaderComboBoxDemo.java */

/*
 * Copyright 2009 Sebastian Haufe Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
 * file except in compliance with the License. You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied. See the License for the specific language governing permissions and limitations under the
 * License.
 */

import java.awt.Component;
import java.awt.Container;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Insets;
import java.awt.LayoutManager;
import java.awt.LayoutManager2;
import java.awt.Rectangle;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.RowFilter;
import javax.swing.SwingConstants;
import javax.swing.WindowConstants;
import javax.swing.event.TableColumnModelEvent;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;

/**
 * A table header with one combo box for each column.
 * 
 * @author Sebastian Haufe
 */
public class JTableHeaderComboBoxDemo implements ItemListener
{

    private TableRowSorter<TableModel> sorter;

    private void newFilter( String selectedText, String column)
    {
        if( selectedText.equals( "Alle" ))
        {
            selectedText = "";
        }
        
        RowFilter<TableModel, Object> rf = null;
        // If current expression doesn't parse, don't update.
        try
        {
            rf = RowFilter.regexFilter( selectedText , Integer.parseInt( column ));
        }
        catch ( java.util.regex.PatternSyntaxException e )
        {
            return;
        }
        sorter.setRowFilter( rf );
    }

    /**
     * Extended table header, adding the preferred height of the layout to its preferred height and revalidates when the
     * dragged column is released.
     */
    private static class JXTableHeader extends JTableHeader
    {

        JXTableHeader( TableColumnModel cm )
        {
            super( cm );
        }

        @Override
        public Dimension getPreferredSize()
        {
            final Dimension size = super.getPreferredSize();
            final LayoutManager layout = getLayout();
            if ( layout != null )
            {
                size.height += layout.preferredLayoutSize( this ).height;
            }
            return size;
        }

        @Override
        public void columnMoved( TableColumnModelEvent e )
        {
            super.columnMoved( e );
            if ( getDraggedColumn() != null )
            {
                revalidate();
                repaint();
            }
        }

        @Override
        public void setDraggedColumn( TableColumn column )
        {
            super.setDraggedColumn( column );
            if ( column == null )
            {
                revalidate();
                repaint();
            }
        }
    }

    /**
     * Layout for table header. Manages components on the table header, using the component index as index in the table
     * model! Calculates the preferred size with a width of zero and a height of the maximum preferred height of all
     * components. Lays out the components in their header rectangle, using an additional margin.
     */
    private static final class TableHeaderSouthLayout
                                                     implements LayoutManager2, java.io.Serializable
    {

        private Insets margin = new Insets( 1, 1, 1, 1 );
        private final Map<Component, Integer> components =
                new HashMap<Component, Integer>();

        /**
         * Get the cell margin.
         * 
         * @return the cell margin
         */
        public Insets getMargin()
        {
            return margin;
        }

        /**
         * Set the cell margin.
         * 
         * @param m
         *            the margin
         * @throws IllegalArgumentException
         *             if {@code margin} is {@code null}
         */
        public void setMargin( Insets m )
        {
            if ( m == null )
            {
                throw new IllegalArgumentException( //
                                                    "margin not allowed null" ); //$NON-NLS-1$
            }
            this.margin = new Insets( m.top, m.left, m.bottom, m.right );
        }

        public void layoutContainer( Container parent )
        {
            final JTableHeader th = ( (JTableHeader) parent );
            final JTable table = th.getTable();
            final int componentCount = th.getComponentCount();
            for ( int i = 0; i < componentCount; i++ )
            {
                final Component comp = th.getComponent( i );
                final Integer columnIndexObj = components.get( comp );
                final int colIndex;
                final int viewIndex;
                if ( table == null
                     || columnIndexObj == null
                     || ( colIndex = columnIndexObj.intValue() ) < 0
                     || ( viewIndex = table.convertColumnIndexToView( colIndex ) ) < 0
                     || viewIndex >= table.getColumnCount() )
                {
                    comp.setBounds( 0, 0, 0, 0 );
                }
                else
                {
                    final Rectangle rect = th.getHeaderRect( viewIndex );
                    final TableColumn draggedColumn = th.getDraggedColumn();
                    if ( draggedColumn != null
                         && draggedColumn.getModelIndex() == colIndex )
                    {
                        rect.x += th.getDraggedDistance();
                        th.setComponentZOrder( comp, 0 );
                    }
                    rect.x += margin.left;
                    rect.y += margin.top;
                    rect.width -= margin.left + margin.right;
                    rect.height -= margin.top + margin.bottom;
                    final Dimension size = comp.getPreferredSize();
                    if ( rect.height > size.height )
                    {
                        rect.y += rect.height - size.height;
                        rect.height = size.height;
                    }
                    comp.setBounds( rect );
                }
            }
        }

        public Dimension preferredLayoutSize( Container parent )
        {
            final JTableHeader th = ( (JTableHeader) parent );
            final JTable table = th.getTable();
            final int componentCount = th.getComponentCount();
            int h = 0;
            for ( int i = 0; i < componentCount; i++ )
            {
                final Component comp = th.getComponent( i );
                final Integer columnIndexObj = components.get( comp );
                final int colIndex;
                final int viewIndex;
                if ( table != null
                     && columnIndexObj != null
                     && ( colIndex = columnIndexObj.intValue() ) >= 0
                     && ( viewIndex = table.convertColumnIndexToView( colIndex ) ) >= 0
                     && viewIndex < table.getColumnCount() )
                {
                    h = Math.max( h, comp.getPreferredSize().height );
                }
            }
            return new Dimension( 0, margin.top + margin.bottom + h );
        }

        public Dimension minimumLayoutSize( Container parent )
        {
            return new Dimension();
        }

        public Dimension maximumLayoutSize( Container target )
        {
            return new Dimension();
        }

        public void removeLayoutComponent( Component comp )
        {
            components.remove( comp );
        }

        public void addLayoutComponent( Component comp, Object constraints )
        {
            if ( !( constraints instanceof Integer ) )
            {
                throw new IllegalArgumentException( //
                                                    "Wrong type: Integer expected" ); //$NON-NLS-1$
            }
            components.put( comp, (Integer) constraints );
        }

        public void addLayoutComponent( String name, Component comp )
        {
        }

        public float getLayoutAlignmentX( Container target )
        {
            return 0.5f;
        }

        public float getLayoutAlignmentY( Container target )
        {
            return 0.5f;
        }

        public void invalidateLayout( Container target )
        {
        }
    }
    
    private void initGuid()
    {
        String[] columnNames = { "First Name",
                                 "Last Name",
                                 "Sport",
                                 "# of Years",
                                 "Vegetarian" };

         Object[][] data = {
                            { "Kathy", "Smith",
                             "Snowboarding", new Integer( 5 ), new Boolean( false ) },
                            { "John", "Doe",
                             "Rowing", new Integer( 3 ), new Boolean( true ) },
                            { "Sue", "Black",
                             "Knitting", new Integer( 2 ), new Boolean( false ) },
                            { "Jane", "White",
                             "Speed reading", new Integer( 20 ), new Boolean( true ) },
                            { "Joe", "Brown",
                             "Pool", new Integer( 10 ), new Boolean( false ) }
         };
         
         /* table without auto-added table header */
         JTable table = new JTable( data, columnNames );
         
         sorter = new TableRowSorter<TableModel>( table.getModel() );
         table.setRowSorter( sorter );
         
         
         
         table.setTableHeader( new JXTableHeader( table.getColumnModel() ) );

         final JTableHeader th = table.getTableHeader();
         final TableCellRenderer defaultRenderer = th.getDefaultRenderer();
         if ( defaultRenderer instanceof JLabel )
         {
             ( (JLabel) defaultRenderer ).setVerticalAlignment( SwingConstants.TOP );
         }
         th.setLayout( new TableHeaderSouthLayout() );

         for( int i = 0; i < table.getModel().getColumnCount(); i ++ )
         {
             th.add( createComboBox( table, i ), Integer.valueOf( i ) );
         }
         
         /* show the test frame */
         final JFrame f = new JFrame( //
                                      "Test Frame: JTableHeaderComboBoxDemo" ); //$NON-NLS-1$
         f.setContentPane( new JScrollPane( table ) );
         f.pack();
         f.setLocationRelativeTo( null );
         f.setDefaultCloseOperation( WindowConstants.EXIT_ON_CLOSE );
         f.setVisible( true );
    }

    /**
     * Test main method.
     * 
     * @param args
     *            ignored
     */
    public static void main( String[] args )
    {
        JTableHeaderComboBoxDemo test = new JTableHeaderComboBoxDemo();
        test.initGuid();
    }

    private JComboBox createComboBox( JTable table, int columnIndex )
    {
        final JComboBox cb = new JComboBox();
        cb.addItem( "Alle" );
        
        for( int i = 0; i < table.getModel().getRowCount(); i ++ )
        {
            cb.addItem( table.getModel().getValueAt( i, columnIndex ) );
        }
        
        cb.setCursor( Cursor.getDefaultCursor() );
        cb.addItemListener( this );
        cb.setName( Integer.toString( columnIndex ) );
        return cb;
    }
    
    public void itemStateChanged( ItemEvent evt )
    {
        if (evt.getStateChange() == ItemEvent.SELECTED )
        {
            System.out.println( ((JComboBox)evt.getSource()).getName() );
            newFilter( ((JComboBox)evt.getSource()).getSelectedItem().toString(), ((JComboBox)evt.getSource()).getName() );
        }
    }
}
 
Hab die Klasse nun schön gemacht.
Ist nun eine eigenständige Klasse welche von JTable erbt.
Funktionen zum Filtern mittels ComboBoxes im Header wurden hinzugefügt.

Code:
package swing;

import java.awt.Component;
import java.awt.Container;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Insets;
import java.awt.LayoutManager;
import java.awt.LayoutManager2;
import java.awt.Rectangle;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.swing.JComboBox;
import javax.swing.JTable;
import javax.swing.RowFilter;
import javax.swing.SwingConstants;
import javax.swing.event.TableColumnModelEvent;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;

import sun.swing.table.DefaultTableCellHeaderRenderer;

/**
 * JTable mit ComboBoxes im Header welche als Filter für die Tabelle dienen<br>
 * <br>
 * Erstellt: 2011-09-02
 * @author MaRk
 */
public class JTableFilterHeader extends JTable implements ItemListener
{
    private static final long serialVersionUID = -8474574634738370571L;
    private static final String ALL_STRING = "(Alle)";

    private TableRowSorter<TableModel> tableRowSorter;
    
    /**
     * Konstruktor
     */
    public JTableFilterHeader(int numRows, int numColumns, Boolean[] filterBoxes) 
    {
        super( new DefaultTableModel( numRows, numColumns) );
        
        init( filterBoxes );
    }
    
    /**
     * Konstruktor
     */
    public JTableFilterHeader()
    {
        super( new DefaultTableModel() );
        
        init( null );
    }
    
    /**
     * Konstruktor
     */
    public JTableFilterHeader( Object[][] rowData, Object[] columnNames, Boolean[] filterBoxes )
    {
        super( new DefaultTableModel( rowData, columnNames) );
        
        init( filterBoxes );
    }
    
    /**
     * Initialisiert die JTable
     */
    private void init( Boolean[] filterBoxes )
    {
        tableRowSorter = new TableRowSorter<TableModel>( getModel() );
        setRowSorter( tableRowSorter );

        setTableHeader( new JXTableHeader( getColumnModel() ) );

        final JTableHeader tableHeader = getTableHeader();
        tableHeader.setLayout( new TableHeaderSouthLayout() );

        DefaultTableCellHeaderRenderer headerRendererTop = new DefaultTableCellHeaderRenderer();
        headerRendererTop.setVerticalAlignment( SwingConstants.TOP );
        
        // Für jede Spalte wird eine ComboBox hinzugefügt
        for ( int i = 0; i < getModel().getColumnCount(); i++ )
        {
            if( filterBoxes != null && filterBoxes[i] == true )
            {
                tableHeader.add( createComboBox( i ), Integer.valueOf( i ) );
                
                TableColumn column = getColumnModel().getColumn( i );
                column.setHeaderRenderer( headerRendererTop );
            }
        }
    }

    /**
     * Erstellt eine ComboBox. Die Items für die ComboBox sind die Inhalte der jeweiligen Spalte (columnIndex)
     * 
     * @param columnIndex
     * @return
     */
    private JComboBox createComboBox( int columnIndex )
    {
        final JComboBox comboBox = new JComboBox();
        comboBox.addItem( ALL_STRING );

        List<String> addedItemList = new ArrayList<String>();
        
        for ( int i = 0; i < getRowCount(); i++ )
        {
            if( getValueAt( i, columnIndex ) != null )
            {
                String valueString = getValueAt( i, columnIndex ).toString();
                
                // Nur wenn das Item noch nicht in der Dropdown-Liste enthalten ist wird es geadded
                if( !addedItemList.contains( valueString ) )
                {
                    comboBox.addItem( getValueAt( i, columnIndex ) );
                    addedItemList.add( valueString );
                }
            }
        }

        comboBox.setCursor( Cursor.getDefaultCursor() );
        comboBox.addItemListener( this );
        comboBox.setName( Integer.toString( columnIndex ) );

        return comboBox;
    }

    /**
     * Aufruf bei jedem change einer ComboBox
     */
    @Override
    public void itemStateChanged( ItemEvent evt )
    {
        if ( evt.getStateChange() == ItemEvent.SELECTED )
        {
            if ( evt.getSource() instanceof JComboBox )
            {
                // Die Tabelle wird nach dem aktuell ausgewählten Einträge ( jeder ComboBox ) gefiltert.
                doFilter();

                // Nach jedem Filter vorgang müssen die ComboBoxes neu befüllt werden
                // Sie werden je nach Inhalt der Tabelle befüllt
                updateComboBoxes();
            }
        }
    }
    
    /**
     * Die ComboBoxes werden upgedated
     */
    private void updateComboBoxes()
    {
        List<String> addedItemList = new ArrayList<String>();
        
        for ( int componentIndex = 0; componentIndex < getTableHeader().getComponentCount(); componentIndex++ )
        {
            if ( getTableHeader().getComponent( componentIndex ) instanceof JComboBox )
            {
                JComboBox comboBox = ( (JComboBox) getTableHeader().getComponent( componentIndex ) );
                Object selectedObject = comboBox.getSelectedItem();
                int columnIndex = Integer.parseInt( comboBox.getName() );

                // Alle Items der ComboBox entfernen
                comboBox.removeAllItems();

                // ItemListener muss entfernt werden. Ansonsten würde eine Endlosschleife entstehen
                comboBox.removeItemListener( this );
                comboBox.addItem( ALL_STRING );

                // ComboBox wird mit den Values der Tabelle befüllt
                for ( int i = 0; i < getRowCount(); i++ )
                {
                    if( getValueAt( i, columnIndex ) != null )
                    {
                        String valueString = getValueAt( i, columnIndex ).toString();
                        
                        // Nur wenn das Item noch nicht in der Dropdown-Liste enthalten ist wird es geadded
                        if( !addedItemList.contains( valueString ) )
                        {
                            comboBox.addItem( getValueAt( i, columnIndex ) );
                            addedItemList.add( valueString );
                        }
                    }
                }

                // Das vorher ausgewählte Item muss wieder gesetzt werden
                comboBox.setSelectedItem( selectedObject );

                // Der ItemListener wird wieder aktiviert
                comboBox.addItemListener( this );
            }
            
            addedItemList.clear();
        }
    }

    /**
     * Die Tabelle wird anhand der ausgewählten Items (von jeder ComboBox) gefiltert
     */
    private void doFilter()
    {
        // Die Liste wird mit der Anzahl der Columns initialisiert
        // Nur in einer Column kann eine ComboBox sein
        List<RowFilter<Object, Object>> rowFilterList = new ArrayList<RowFilter<Object, Object>>( getColumnCount() );

        for ( int column = 0; column < getTableHeader().getComponentCount(); column++ )
        {
            if ( getTableHeader().getComponent( column ) instanceof JComboBox )
            {
                JComboBox cb = ( (JComboBox) getTableHeader().getComponent( column ) );
                String selectedText = cb.getSelectedItem().toString();
                int row = Integer.parseInt( cb.getName() );

                if ( selectedText.equals( ALL_STRING ) )
                {
                    selectedText = "";
                }

                // If current expression doesn't parse, don't update.
                try
                {
                    rowFilterList.add( RowFilter.regexFilter( selectedText, row ) );
                }
                catch ( java.util.regex.PatternSyntaxException e )
                {
                    e.printStackTrace();
                }
            }
        }

        tableRowSorter.setRowFilter( RowFilter.andFilter( rowFilterList ) );
    }
    
    /**
     * Befüllt einen ColumnHeader
     * @param headerValue
     */
    public void addColumn( String headerValue, Object[] columnData, boolean filterBox )
    {
        // Hier müssenw ir das autoCreate ausschalten und die Column händisch adden
        // Falls die Methode ((DefaultTableModel)getModel()).addColumn( headerValue, columnData );
        // verwendet werden würde, dann würden alle Änderungen der anderen Columns rückgängig gemacht werden
        // Durch addColumn würde die ganze Table auf ihren default-Wert zurückgesetzt werden.
        // zb. auch das VerticalAligment der einzelnen Headers
        setAutoCreateColumnsFromModel( false );
        
        DefaultTableModel model = (DefaultTableModel)getModel();
        TableColumn columnToAdd = new TableColumn(model.getColumnCount());

        columnToAdd.setHeaderValue( headerValue );
        addColumn( columnToAdd );
        model.addColumn(headerValue.toString(), columnData);
        
        // Soll eine ComboBox als Filter eingebaut werden?
        if( filterBox )
        {
            final JTableHeader tableHeader = getTableHeader();
            
            tableHeader.add( createComboBox( getModel().getColumnCount()-1 ), Integer.valueOf( getModel().getColumnCount()-1 ) );
            
            updateComboBoxes();
        }
    }
    
    /**
     * Eine Liste von Rows wird hinzugefügt
     * @param rowList
     */
    public void addRows( LinkedList<LinkedList<Object>> rowList )
    {
        for( LinkedList<Object> row : rowList )
        {
            addRow( row );
        }
        
        updateComboBoxes();
    }
    
    /**
     * Eine Liste von Rows wird hinzugefügt
     * @param rowList
     */
    public void addRows( Object[][] rowList )
    {
        for( Object[] row : rowList )
        {
            addRow( row );
        }
        
        updateComboBoxes();
    }
    
    /**
     * Eine Row wird befüllt
     * @param rowValue
     */
    public void addRow( LinkedList<Object> rowValue )
    {
        Object[] rowValueArray = new Object[ rowValue.size() ];
        
        for( int i = 0; i < rowValue.size(); i ++ )
        {
            rowValueArray[i] = rowValue.get( i );
        }
        
        addRow( rowValueArray );
        
        updateComboBoxes();
    }
    
    /**
     * Eine Row wird befüllt
     * @param rowValue
     */
    public void addRow( Object[] rowValue )
    {
        ((DefaultTableModel)getModel()).addRow( rowValue );
        
        updateComboBoxes();
    }

    /**
     * Layout for table header. Manages components on the table header, using the component index as index in the table
     * model! Calculates the preferred size with a width of zero and a height of the maximum preferred height of all
     * components. Lays out the components in their header rectangle, using an additional margin. 
     * 
     * Durch das hinzufügen der ComboBoxes muss die Höhe des Headers angepasst werden.
     */
    private final class TableHeaderSouthLayout implements LayoutManager2, Serializable
    {
        private static final long serialVersionUID = 8709582749968401459L;

        private Insets margin = new Insets( 1, 1, 1, 1 );

        private final Map<Component, Integer> components = new HashMap<Component, Integer>();

        /**
         * Get the cell margin.
         * 
         * @return the cell margin
         */
        @SuppressWarnings("unused")
        public Insets getMargin()
        {
            return margin;
        }

        /**
         * Set the cell margin.
         * 
         * @param m
         *            the margin
         * @throws IllegalArgumentException
         *             if {@code margin} is {@code null}
         */
        @SuppressWarnings("unused")
        public void setMargin( Insets m )
        {
            if ( m == null )
            {
                throw new IllegalArgumentException( "margin not allowed null" );
            }
            this.margin = new Insets( m.top, m.left, m.bottom, m.right );
        }

        @Override
        public void layoutContainer( Container parent )
        {
            final JTableHeader th = ( (JTableHeader) parent );
            final JTable table = th.getTable();
            final int componentCount = th.getComponentCount();

            for ( int i = 0; i < componentCount; i++ )
            {
                final Component comp = th.getComponent( i );
                final Integer columnIndexObj = components.get( comp );
                final int colIndex;
                final int viewIndex;

                if ( table == null
                     || columnIndexObj == null
                     || ( colIndex = columnIndexObj.intValue() ) < 0
                     || ( viewIndex = table.convertColumnIndexToView( colIndex ) ) < 0
                     || viewIndex >= table.getColumnCount() )
                {
                    comp.setBounds( 0, 0, 0, 0 );
                }
                else
                {
                    final Rectangle rect = th.getHeaderRect( viewIndex );
                    final TableColumn draggedColumn = th.getDraggedColumn();

                    if ( draggedColumn != null && draggedColumn.getModelIndex() == colIndex )
                    {
                        rect.x += th.getDraggedDistance();
                        th.setComponentZOrder( comp, 0 );
                    }

                    rect.x += margin.left;
                    rect.y += margin.top;
                    rect.width -= margin.left + margin.right;
                    rect.height -= margin.top + margin.bottom;
                    final Dimension size = comp.getPreferredSize();

                    if ( rect.height > size.height )
                    {
                        rect.y += rect.height - size.height;
                        rect.height = size.height;
                    }

                    comp.setBounds( rect );
                }
            }
        }

        @Override
        public Dimension preferredLayoutSize( Container parent )
        {
            final JTableHeader th = ( (JTableHeader) parent );
            final JTable table = th.getTable();
            final int componentCount = th.getComponentCount();
            int h = 0;

            for ( int i = 0; i < componentCount; i++ )
            {
                final Component comp = th.getComponent( i );
                final Integer columnIndexObj = components.get( comp );
                final int colIndex;
                final int viewIndex;

                if ( table != null
                     && columnIndexObj != null
                     && ( colIndex = columnIndexObj.intValue() ) >= 0
                     && ( viewIndex = table.convertColumnIndexToView( colIndex ) ) >= 0
                     && viewIndex < table.getColumnCount() )
                {
                    h = Math.max( h, comp.getPreferredSize().height );
                }
            }

            return new Dimension( 0, margin.top + margin.bottom + h );
        }

        @Override
        public Dimension minimumLayoutSize( Container parent )
        {
            return new Dimension();
        }

        @Override
        public Dimension maximumLayoutSize( Container target )
        {
            return new Dimension();
        }

        @Override
        public void removeLayoutComponent( Component comp )
        {
            components.remove( comp );
        }

        @Override
        public void addLayoutComponent( Component comp, Object constraints )
        {
            if ( !( constraints instanceof Integer ) )
            {
                throw new IllegalArgumentException( "Wrong type: Integer expected" );
            }
            components.put( comp, (Integer) constraints );
        }

        @Override
        public void addLayoutComponent( String name, Component comp )
        {
        }

        @Override
        public float getLayoutAlignmentX( Container target )
        {
            return 0.5f;
        }

        @Override
        public float getLayoutAlignmentY( Container target )
        {
            return 0.5f;
        }

        @Override
        public void invalidateLayout( Container target )
        {
        }
    }

    /**
     * Extended table header, adding the preferred height of the layout to its preferred height and revalidates when the
     * dragged column is released. 
     * 
     * Durch das hinzufügen der ComboBoxes im Header muss die Headersize(durch {@link TableHeaderSouthLayout}) erhöht werden. 
     * JXTableHeader stellt sicher, dass die Höhe auch beim verschieben der Spalten gleich bleibt.
     */
    private class JXTableHeader extends JTableHeader
    {
        private static final long serialVersionUID = -4435249644348771055L;

        JXTableHeader( TableColumnModel cm )
        {
            super( cm );
        }

        @Override
        public Dimension getPreferredSize()
        {
            final Dimension size = super.getPreferredSize();
            final LayoutManager layout = getLayout();

            if ( layout != null )
            {
                size.height += layout.preferredLayoutSize( this ).height;
            }

            return size;
        }

        @Override
        public void columnMoved( TableColumnModelEvent e )
        {
            super.columnMoved( e );

            if ( getDraggedColumn() != null )
            {
                revalidate();
                repaint();
            }
        }

        @Override
        public void setDraggedColumn( TableColumn column )
        {
            super.setDraggedColumn( column );

            if ( column == null )
            {
                revalidate();
                repaint();
            }
        }
    }

}
 
Zuletzt bearbeitet:
Zurück