Results 1 to 2 of 2
  1. #1
    neha_sinha is offline Member
    Join Date
    Jul 2010
    Posts
    10
    Rep Power
    0

    Default selecting column names dynamically from table column header

    hello,

    could anyone please help me out as how to select column names dynamically from the table column header.the table column header has fewer columns displayed than what declared in the table column model.

    regards,
    neha

  2. #2
    camickr is offline Senior Member
    Join Date
    Jul 2009
    Posts
    1,236
    Rep Power
    7

    Default

    Table Column Manager allows the user to right click on the table header to control which columns are visible.

    Java Code:
    import java.awt.*;
    import java.util.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
     
    public class TableColumnManager implements MouseListener, ActionListener
    {
    	//
    	private static final String HIDDEN_COLUMN = "HiddenColumn:";
     
    	//  Reference to the Singleton instance of this class
    	private static TableColumnManager singleton;
     
        /**
         *  Use a private constructor so we can create a Singleton.
         */
    	private TableColumnManager()
    	{
    	}
     
        /**
         *  Get the Singleton instance of the TableColumnManager.
         *
         *  @return  the Singlton instance of TableColumnManager
         */
    	private static TableColumnManager getInstance()
    	{
    		if (singleton == null)
    		{
    			singleton = new TableColumnManager();
    		}
     
    		return singleton;
    	}
     
        /**
         *  Add support for the management of visible TableColumns
         *  for a given JTable.
         *
         *  @param  table the table to provide support for
         */
    	public static void install(JTable table)
    	{
    		table.getTableHeader().addMouseListener( getInstance() );
    	}
     
        /**
         *  Remove support for the management of visible TableColumns
         *  for a given JTable.
         *
         *  @param  table the table to remove support from
         */
    	public static void uninstall(JTable table)
    	{
    		table.getTableHeader().removeMouseListener( getInstance() );
    	}
     
        /**
         *  Hide a column from view in the table.
         *
         *  @param  table        the table from which the column is removed
         *  @param  modelColumn  the column index from the TableModel
         *                       of the column to be removed
         */
    	public static void hideColumn(JTable table, int modelColumn)
    	{
    		int viewColumn = table.convertColumnIndexToView( modelColumn );
     
    		if (viewColumn != -1)
    		{
    			TableColumn column = table.getColumnModel().getColumn(viewColumn);
    			hideColumn(table, column);
    		}
    	}
     
        /**
         *  Hide a column from view in the table.
         *
         *  @param  table        the table from which the column is removed
         *  @param  columnName   the column name of the column to be removed
         */
    	public static void hideColumn(JTable table, String columnName)
    	{
    		try
    		{
    			TableColumnModel tcm = table.getColumnModel();
    			int index = tcm.getColumnIndex( columnName );
    			TableColumn column = tcm.getColumn( index );
    			hideColumn(table, column);
    		}
    		catch(IllegalArgumentException e) {}
    	}
     
        /**
         *  Hide a column from view in the table.
         *
         *  @param  table   the table from which the column is removed
         *  @param  column  the TableColumn to be removed from the
         *                  TableColumnModel of the specified table
         */
    	public static void hideColumn(JTable table, TableColumn column)
    	{
    		table.getColumnModel().removeColumn( column );
     
    		//  Save the column so it can be redisplayed
     
    		ArrayList list = (ArrayList)table.getClientProperty(HIDDEN_COLUMN);
    
    		if (list == null)
    		{
    			list = new ArrayList();
    			table.putClientProperty(HIDDEN_COLUMN, list);
    		}
    
    		list.add(column);
    	}
    
        /**
         *  Show a hidden column in the table.
         *
         *  @param  table        the table to which the column is added
         *  @param  modelColumn  the column index from the TableModel
         *                       of the column to be added
         */
    	public static void showColumn(JTable table, int modelColumn)
    	{
    		ArrayList list = (ArrayList)table.getClientProperty(HIDDEN_COLUMN);
    
    		if (list == null) return;
    
    		ListIterator it = list.listIterator();
    
    		while (it.hasNext())
    		{
    			TableColumn column = (TableColumn)it.next();
    
    			if (column.getModelIndex() == modelColumn)
    			{
    				table.getColumnModel().addColumn( column );
    				it.remove();
    				break;
    			}
    		}
    	}
    
        /**
         *  Show a hidden column in the table.
         *
         *  @param  table        the table to which the column is added
         *  @param  columnName   the column name from the TableModel
         *                       of the column to be added
         */
    	public static void showColumn(JTable table, String columnName)
    	{
    		ArrayList list = (ArrayList)table.getClientProperty(HIDDEN_COLUMN);
    
    		if (list == null) return;
    
    		ListIterator it = list.listIterator();
    
    		while (it.hasNext())
    		{
    			TableColumn column = (TableColumn)it.next();
    
    			if (column.getHeaderValue().equals(columnName))
    			{
    				table.getColumnModel().addColumn( column );
    				it.remove();
    				break;
    			}
    		}
    	}
    
    	//  Implement the MouseListener
    
    	public void mousePressed(MouseEvent e)
    	{
    		checkForPopup( e );
    	}
     
    	public void mouseReleased(MouseEvent e)
    	{
    		checkForPopup( e );
    	}
     
    	public void mouseClicked(MouseEvent e) {}
    	public void mouseEntered(MouseEvent e) {}
    	public void mouseExited(MouseEvent e) {}
     
    	private void checkForPopup(MouseEvent e)
    	{
    		if (e.isPopupTrigger())
    		{
    			JTableHeader header = (JTableHeader)e.getComponent();
    			int column = header.columnAtPoint( e.getPoint() );
    			showPopup(header.getTable(), column);
    		}
    	}
     
        /**
         *  Show a hidden column in the table.
         *
         *  @param  table        the table to which the column is added
         *  @param  columnName   the column name from the TableModel
         *                       of the column to be added
         */
    	public static void showPopup(JTable table, int tableColumn)
    	{
    		int columns = table.getModel().getColumnCount();
    		JCheckBoxMenuItem[] items = new JCheckBoxMenuItem[columns];
     
    		//  Create menu items for hidden columns
     
       		ArrayList list = (ArrayList)table.getClientProperty(HIDDEN_COLUMN);
     
       		if (list != null)
       		{
    			ListIterator it = list.listIterator();
     
    			while (it.hasNext())
    			{
    				TableColumn column = (TableColumn)it.next();
    				String columnName = column.getHeaderValue().toString();
    				JCheckBoxMenuItem item = new JCheckBoxMenuItem( columnName );
    				item.setSelected( false );
    				item.addActionListener(getInstance());
    				items[column.getModelIndex()] = item;
    			}
       		}
     
    		//  Create menu items for visible columns
    
    		TableColumnModel columnModel = table.getColumnModel();
    		int columnCount = columnModel.getColumnCount();
    
    		for (int i = 0; i < columnCount; i++)
    		{
    			TableColumn column = columnModel.getColumn(i);
    			String columnName = column.getHeaderValue().toString();
    			JCheckBoxMenuItem item = new JCheckBoxMenuItem( columnName );
    			item.setSelected( true );
    			item.addActionListener(getInstance());
    
    			if (columnCount == 1)
    				item.setEnabled( false );
    
    			items[column.getModelIndex()] = item;
    		}
    
    
    		//  Create popup menu from array of menu items.
    		//  Override method to select the specified menu item.
    		//  (ie. this is a bug? fix)
    
    		JPopupMenu popup = new JPopupMenu()
    		{
    			public void setSelected(Component sel)
    			{
    				int index = getComponentIndex( sel );
    				getSelectionModel().setSelectedIndex(index);
    				final MenuElement me[] = new MenuElement[2];
    				me[0]=(MenuElement)this;
    				me[1]=getSubElements()[index];
    
    				SwingUtilities.invokeLater(new Runnable()
    				{
    					public void run()
    					{
    						MenuSelectionManager.defaultManager()
    							.setSelectedPath(me);
    					}
    				});
    			}
    		};
    
    		for (int i = 0; i < items.length; i++)
    		{
    			if (items[i] != null)
    			{
    				popup.add( items[i] );
    			}
    		}
    
    		//  Display the popup below the TableHeader
    
    		JTableHeader header = table.getTableHeader();
    		Rectangle r = header.getHeaderRect( tableColumn );
    		popup.show(header, r.x, r.height);
    		int modelColumn = table.convertColumnIndexToModel( tableColumn );
    		popup.setSelected( items[modelColumn] );
    	}
    
        /**
         *  Responsible for processing the ActionEvent. A column will either be
         *  added to the table or removed from the table depending on the state
         *  of the menu item that was clicked.
         *
         * @param event the ActionEvent.
         */
    	public void actionPerformed(ActionEvent event)
        {
    		JMenuItem item = (JMenuItem)event.getSource();
    		JPopupMenu popup = (JPopupMenu)item.getParent();
    		JTableHeader header = (JTableHeader)popup.getInvoker();
    		JTable table = header.getTable();
    
    		if (item.isSelected())
    		{
    			showColumn(table, item.getText());
    		}
    		else
    		{
    			hideColumn(table, item.getText());
    		}
    	}
    
    	public static void main(String[] args)
    	{
    		JTable table = new JTable( new DefaultTableModel(5, 10) );
    
    		TableColumnManager.install(table);
    		TableColumnManager.hideColumn(table, 2);
    		TableColumnManager.hideColumn(table, "E");
     
    		JFrame frame = new JFrame();
    		frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    		frame.getContentPane().add( new JScrollPane(table) );
    		frame.pack();
    		frame.setVisible( true );
    	 }
    }

Similar Threads

  1. Replies: 4
    Last Post: 02-05-2011, 07:47 PM
  2. table column sort
    By new2java2009 in forum New To Java
    Replies: 8
    Last Post: 04-16-2010, 02:17 AM
  3. Non-Editable Table Column
    By ld_pvl in forum AWT / Swing
    Replies: 6
    Last Post: 08-03-2009, 07:35 PM
  4. Sorting a SWT table by column
    By Java Tip in forum SWT Tips
    Replies: 0
    Last Post: 07-11-2008, 04:07 PM
  5. Replies: 0
    Last Post: 11-08-2007, 09:48 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •