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!
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: