JTextFields above column headers in JTable

I am looking for a way to put a single row above (for filtering purposes) the table header in a JTable. Right now I am using JTextFields above my table for the filters, but as the columns are resized or moved so would the text fields have to be. So I am thinking putting a row above the table header would be appropriate.
Any suggestions or examples in this area?

Hello
I've been working on something similar (filters above a JXTable) and i managed to get it working. So i'm putting it on this thread if someone find it with google :)
The code for moving / resizing columns works fine, but the code for removing/adding columns doesn't work very well because it only allows one removed column at a time, or that you add the columns in the correct order.
My solution is a bit different. I put a listener on the column property "visible", associated with the filter component above the column. That way, when i remove (hide) a column, the filter component removes itself from the panel, and when i reactivate the column, the component adds itself to the panel.
Because the property change event is fired after the columnadded / columnmoved event, i have to use invokeLater thread to actually move the component at its right position.
Here's the code for the moved/resized listener:
import java.awt.Component;
import java.awt.Dimension;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.TableColumnModelEvent;
import javax.swing.event.TableColumnModelListener;
import javax.swing.table.TableColumnModel;
import fr.dga.gesma.catalyse.ihm.beans.FilterPanel;
public class ExternalHeaderColumnModelListener implements TableColumnModelListener {
    private JPanel filterRow;
    private JTable table;
    public ExternalHeaderColumnModelListener(JPanel header, JTable table) {
        filterRow = header;
        this.table = table;
    public void columnAdded(TableColumnModelEvent e) {
    public void columnRemoved(TableColumnModelEvent e) {
    public void columnMarginChanged(ChangeEvent e)
        TableColumnModel tcm = table.getColumnModel();
        int columns = tcm.getColumnCount();
        for (int i = 0; i < columns; i ++)
            FilterPanel filtre = (FilterPanel)filterRow.getComponent( i );
            Dimension d = filtre.getPreferredSize();
            d.width = tcm.getColumn(i).getWidth();
            filtre.setPreferredSize( d );
        SwingUtilities.invokeLater(new Runnable()
            public void run()
                filterRow.revalidate();
    public void columnMoved(TableColumnModelEvent e)
        final int toIndex = e.getToIndex();
        final int fromIndex = e.getFromIndex();
        // Delaying so the component exists when we move it
        SwingUtilities.invokeLater(new Runnable()
            public void run()
                Component moved = filterRow.getComponent(fromIndex);
                if (moved != null) {
                    filterRow.remove(fromIndex);
                    filterRow.add(moved, toIndex);
                    filterRow.validate();
    public void columnSelectionChanged(ListSelectionEvent e) {}and the code for the filter component (listener part) :
    private Container parent = null;
    // Taken from ColumnControlButton (JXTable component)
    // This listener is added to the TableColumn associated to this filter component
    protected PropertyChangeListener createPropertyChangeListener() {
        return new PropertyChangeListener() {
            public void propertyChange(PropertyChangeEvent evt) {
                if ("visible".equals(evt.getPropertyName())) {
                    updateFromColumnVisible((Boolean) evt.getNewValue());
     * Hides or shows the filter component. This
     * is called on change of tablecolumn's <code>visible</code> property.
     * @param visible column visible state to synch to.
    private void updateFromColumnVisible(boolean visible) {
        if (visible) {
            if (parent != null) {
                parent.add(this);
                parent.validate();
        } else {
            parent = this.getParent();
            if (parent != null) {
                parent.remove(this);
                parent.validate();
    }Hope this helps someone :)

Similar Messages

  • How can I add custom right-click-menu to column headers in JTable?

    Can anyone point me to a topic on how to customize a popup menu for column headers in JTable? Specifically, I want to add things like "auto-size column" and "hide column".
    Thanks,
    Matt

    Right-click on your table.  Then go to Advanced->Runtime Shortcut Menu->Edit.
    There are only two ways to tell somebody thanks: Kudos and Marked Solutions
    Unofficial Forum Rules and Guidelines

  • How can I set column headers in JTable?

    I only want to set 3 column headers in JTable (without TabelModel). Can you help me?

    Hello dn77,
    Here's is a little sample I just rigged up, hope it helps.
    import java.awt.*;
    import javax.swing.*;
    public class TestOne{
         public static void main(String arg[]) {
              Object rows[][] = {
                   {"One", "1", "I"},
                   {"Two", "2", "II"},
                   {"Three", "3", "III"},
                   {"Four", "4", "IV"},
                   {"Five", "5", "V"},
                   {"Six", "6", "VI"},
                   {"Seven", "7", "VII"},
                   {"Eight", "8", "VIII"},
                   {"Nine", "9", "IX"},
                   {"Ten", "10", "X"},
                   {"Eleven", "11", "XI"},
                   {"Twelve", "12", "XII"},
                   {"Thirteen", "13", "XIII"},
                   {"Fourteen", "14", "XIV"},
                   {"Fifteen", "15", "XV"},
                   {"Sixteen", "16", "XVI"},
                   {"Seventeen", "17", "XVII"},
                   {"Eighteen", "18", "XVIII"},
                   {"Nineteen", "19", "XIX"},
                   {"Twenty", "20", "XX"}
              String headers[] = {"Notation", "Decimal", "Roman"};
              JFrame frame = new JFrame("3 Column header");
              JTable table = new JTable(rows, headers);
              JScrollPane scrollPane = new JScrollPane(table);
              frame.getContentPane().add(scrollPane, BorderLayout.CENTER);
              frame.setSize(300,150);
              frame.setVisible(true);
    }-Merwyn,
    Developer Technical Support,
    http://www.sun.com/developers/support.

  • Custom column headers for JTable in JScrollPane

    I want a heirachical header structure on a scrolled JTable. I've successfully generated a second JTableHeader which moves it's tabs with the normal header. If I add the secondary JTableHeader into the container above the whole scroll pane it's does almost what I want, but it's not quite correctly aligned.
    What I want to do is to put both the automaticaly generated JTableHeader and my extra one into the JScrollPane's column header area.
    I wrapped the two headers together into a vertical Box and tried calling the setColumnHeaderView() on the scrollpane, and then creating a JViewport and using setColumnHeader(). Niether seems to have any effect. The basic table header obstinately remains unaltered.
    There seems to be some special processing going on when JTable and JScrollPane get together, but I can't understand how replacing the column header viewport can be ineffective.

    Thanks. I think I've just cracked it more thoroughly, though. [I found this bug report|http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5032464]. This has guided me to a work-around that seems stable so far. I'm using an extended JTable class anyway (mostly to do with table header width behaviour). I've added a field to my own table class and the following override:
    The trick is to work out where the dirty deed is done, having search all the scroll pane related classes for special casing JTable.
    public class STable extends JTable {
        @Override
        protected void configureEnclosingScrollPane() {
            if (secondaryHeader == null) {
                super.configureEnclosingScrollPane();
            } else {
                Container p = getParent();
                if (p instanceof JViewport) {
                    Container gp = p.getParent();
                    if (gp instanceof JScrollPane) {
                        JScrollPane scrollPane = (JScrollPane) gp;
                        // Make certain we are the viewPort's view and not, for
                        // example, the rowHeaderView of the scrollPane -
                        // an implementor of fixed columns might do this.
                        JViewport viewport = scrollPane.getViewport();
                        if (viewport == null || viewport.getView() != this) {
                            return;
                        JPanel hdrs = new JPanel();
                        hdrs.setLayout(new BorderLayout());
                        hdrs.add(secondaryHeader.getHeader(), BorderLayout.NORTH);
                        hdrs.add(getTableHeader(), BorderLayout.SOUTH);
                        scrollPane.setColumnHeaderView(hdrs);
                        //  scrollPane.getViewport().setBackingStoreEnabled(true);
                        Border border = scrollPane.getBorder();
                        if (border == null || border instanceof UIResource) {
                            Border scrollPaneBorder =
                                    UIManager.getBorder("Table.scrollPaneBorder");
                            if (scrollPaneBorder != null) {
                                scrollPane.setBorder(scrollPaneBorder);
        }I'm hopeful that will prevent the column header view from being overwritten by later layout operations.

  • JTable column headers missing..kindly help...

    Hello there!
    I have written a program that ultimately deals with database connectivity, but my problem is got more to do with JTable. that's why i decided to post my doubt here.
    my program displays a JTable by reading fields form a database.
    But you see, the column headers are missing!!
    I have used the concept of DefaultTableModel, i first searched google and came upon a website: www.exampledepot.com and studied the sample codes on how insert fields into a JTable using the above....
    i swear to god i have done the exact same things..
    Could you please help me out??
    Thankyou very much and have a great day!
    :-)

    done that alreadyThen your problem is solved?
    Or does that mean that you had already done it and no headings showed up? In that case there's something wrong with your code.
    And Swing questions should be posted in the Swing forum.

  • JTable column headers not displaying using custom table model

    Hi,
    I'm attempting to use a custom table model (by extending AbstractTableModel) to display the contents of a data set in a JTable. The table is displaying the data itself correctly but there are no column headers appearing. I have overridden getColumnName of the table model to return the correct header and have tried playing with the ColumnModel for the table but have not been able to get the headers to display (at all).
    Any ideas?
    Cheers

    Class PublicationTableModel:
    public class PublicationTableModel extends AbstractTableModel
        PublicationManager pubManager;
        /** Creates a new instance of PublicationTableModel */
        public PublicationTableModel(PublicationManager pm)
            super();
            pubManager = pm;
        public int getColumnCount()
            return GUISettings.getDisplayedFieldCount();
        public int getRowCount()
            return pubManager.getPublicationCount();
        public Class getColumnClass(int columnIndex)
            Object o = getValueAt(0, columnIndex);
            if (o != null) return o.getClass();
            return (new String()).getClass();
        public String getColumnName(int columnIndex)
            System.out.println("asked for column name "+columnIndex+" --> "+GUISettings.getColumnName(columnIndex));
            return GUISettings.getColumnName(columnIndex);
        public Publication getPublicationAt(int rowIndex)
            return pubManager.getPublicationAt(rowIndex);
        public Object getValueAt(int rowIndex, int columnIndex)
            Publication pub = (Publication)pubManager.getPublicationAt(rowIndex);
            String columnName = getColumnName(columnIndex);
            if (columnName.equals("Address"))
                if (pub instanceof Address) return ((Address)pub).getAddress();
                else return null;
            else if (columnName.equals("Annotation"))
                if (pub instanceof Annotation) return ((Annotation)pub).getAnnotation();
                else return null;
            etc
           else if (columnName.equals("Title"))
                return pub.getTitle();
            else if (columnName.equals("Key"))
                return pub.getKey();
            return null;
        public boolean isCellEditable(int rowIndex, int colIndex)
            return false;
        public void setValueAt(Object vValue, int rowIndex, int colIndex)
        }Class GUISettings:
    public class GUISettings {
        private static Vector fields = new Vector();
        private static Vector classes = new Vector();
        /** Creates a new instance of GUISettings */
        public GUISettings() {
        public static void setFields(Vector f)
            fields=f;
        public static int getDisplayedFieldCount()
            return fields.size();
        public static String getColumnName(int columnIndex)
            return (String)fields.elementAt(columnIndex);
        public static Vector getFields()
            return fields;
    }GUISettings.setFields has been called before table is displayed.
    Cheers,
    garsher

  • Remove Column Headers from a JTable in a JScrollPane

    Hi,
    I'm just wondering how to remove the column headers from a JTable in a JScrollPane.

    Here are two ways to do it, with different visual outcomes...
    import javax.swing.*;
    public class Test {
        public static void main(String[] args) {
            Object[][] rowData = {{"A", "B"}, {"C", "D"}};
            Object[] columnNames = {"col 1", "col 2"};
            JTable table1 = new JTable(rowData, columnNames);
            table1.getTableHeader().setVisible(false);
            JScrollPane sp1 = new JScrollPane(table1);
            JTable table2 = new JTable(rowData, columnNames);
            final JScrollPane sp2 = new JScrollPane(table2);
            JPanel contentPane = new JPanel();
            contentPane.add(sp1);
            contentPane.add(sp2);
            final JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setContentPane(contentPane);
            f.pack();
            SwingUtilities.invokeLater(new Runnable(){
                public void run() {
                    sp2.setColumnHeader(null);
                    f.setLocationRelativeTo(null);
                    f.setVisible(true);
    }

  • Cant see jtable column headers

    I have my jtable in a container and i am displaying that container in a jframe. I cant see the table column headers. I cant use a jscrollpane and need to make the table headers visible. I can see the table fine with all its information in it. When I do a System.out.println(TableModel.getColumnName(int)); i get the correct column header name so I know that the column headers are existing. I would appreciate any help that you can give

    the last answer did not help me out. I reposted this with more information, such as i am placing my table in a container and not in a scrollpane. I added the code below and it still did not work
    content.add(jt.getTableHeader(), BorderLayout.NORTH);
    content.add(jt, BorderLayout.CENTER);
    I can still only see the table. I pasted code below where I create my table and repaint it. I have it set up where my table is in a JPanel. I have is set up so that I can move it around and resize it with the mouse. This all works and I can see the table but there are no headers.
    public FigTable(DefaultTableModel inTableModel, LEditor inLEditor)
              super(50, 50, 350, 200);
              setLineColor(Color.blue);
              setFillColor(ColorMenu.kColorOfNoFill);
              fEditor = inLEditor;
              content = fEditor.getGEFPanel().getDrawingPanel();
              importTable(inTableModel);
              fEditor.init();
              fEditor.inval();
    public void importTable(DefaultTableModel inTableModel)
              jt = new JTable(inTableModel);
              tRows = jt.getRowCount();
              tColumns = jt.getColumnCount();
              content.add(jt, BorderLayout.CENTER);
              content.add(jt.getTableHeader(), BorderLayout.NORTH);
    public void paint(Graphics g)
              jt.setBounds(_x, y, w, _h);
              if (_h >= tRows && tRows != 0)
              jt.setRowHeight(_h / tRows);
              if (isSelected())
                   drawHandles(g);
              if (_filled && (getFillColor() != null))
                   jt.setBackground(getFillColor());
              if (getLineColor() != null)
                   jt.setGridColor(getLineColor());
                   jt.setBorder(BorderFactory.createLineBorder(getLineColor()));
         }

  • Export JTable Column headers to Excel document

    Hello all!!! I am having a small problem while trying to export some data from a jTable to an excel document.
    I have a jTable and I use a custom TableModel with this:
    private String[] columnNames = {"First", "Second", "Third", "Forth"};as names for each column of the table.
    The thing I am trying to do is to export exactly the same "headers" from the columns of the jTable to the excel spreadsheet using Jakarta POI. Unfortunately I don't know how to do it and I haven't found anything yet on this forum. Can anyone help me with this?
    In simple words I want to know how I can have the same headers from my jTable columns, with the headers from the excel doument I will create.
    Many thanks in advanve!!!
    Kostas

    Thank you for your reply first of all. The problem is how to get the heading text and how to put it to the excel's first row OR to excels "headings" (if it is possible...). [in other words replace A,B,C,D from the excel document with the headers I get from the jTable...] .
    I hope now you can see what I am looking for... If there is no solution to this please tell me what are the alternatives. (B) could be a good example.
    Thanks you very much!!
    Kostas

  • JTable column headers missing

    I created a JTable using:
    JTable table = new JTable(v,cN);
    where v is my vector that holds the data and cN is a vector to hold the column names as below:
    Vector cN = new Vector();
         cN.add("Registry Keys");
         cN.add("Program Name");
         cN.add("Key Type");
         cN.add("Drive");
         cN.add("Location");
         cN.add("Leave");It displays the table fine with the data and as I add or remove entries in the cN vector it adds and removes columns - but doesn't display column headers? Any help appreciated.

    Are you using a scrollpane? If not, you have to get the Table Header component and place it appropriately.

  • JTable Column Headers are Squashed!

    Hi there,
    I'm using JBuilder, and have created a simple enough JTable that I place inside a JScrollPane. I am using my own implementation of the AbstractTable model.
    When I run the code, the Column headers are only about 5 pixels high! I have hunted around the JBuilder code (which if you have used JBuilder you will know is extensive!), but it doesn't seem to be doing anything extraordinary.
    So has anyone else had this problem? If so, what did you do to rectify.
    Yours hopefully
    Richard

    Hello there, my abstract implementation looks a little like this:
      public static final String columns[] = { "", "Request Id", "Date", "Component Name", "Version", "Type" };
      public String getColumnName(int columnIndex) {
        return columns[columnIndex];
      public Class getColumnClass(int columnIndex) {
        if (columnIndex == 0) {
          return Boolean.class;
        } else if (columnIndex == 1) {
          return Integer.class;
        } else {
          return String.class;
      }Thanks
    Richard

  • JTable Column Headers

    I want to create a JTable so that the table doesn't have any column headers. Right now I am using my own implementation of the AbstractTableModel Class for use with the tables, but if I leave out the public String getColumnName(int col) method, it makes the headers A, B, C, ... and if I set the column headers up with a blank String, it leaves an obvious thin empty header at the top. Any suggestions on how I can completely leave the column headers off?

    call the method on JTable
    table.setTableHeader(null);
    that will do the trick;
    cheers
    krishna

  • JTable -showing column headers and displaying multi-line strings

    Hi,
    This is two questions really.
    #1 - Does anyone know why my column headers aren't showing in my jtable using the model below?
    #2 - Does anyone know how I can display, mulitple line strings in a jtable? Currently my newline character ('\n') is just being displayed as a character.
    any help very much appreciated,
    Tom
    private class TaskHistoryTableModel extends AbstractTableModel {
    private List taskHistory = new ArrayList();
    public Object getValueAt(int row, int col) {
    if (col == 0) {
    return ((TaskHistoryItem) taskHistory.get(row)).getText();
    } else {
    return ((TaskHistoryItem) taskHistory.get(row)).getDate().getTime();
    public int getRowCount() {
    return taskHistory == null ? 0 : taskHistory.size();
    public int getColumnCount() {
    return 2;
    /** Getter for property taskHistory.
    * @return Value of property taskHistory.
    public List getTaskHistory() {
    return taskHistory;
    /** Setter for property taskHistory.
    * @param taskHistory New value of property taskHistory.
    public void setTaskHistory(List taskHistory) {
    this.taskHistory = taskHistory;
    public String getColumnName (int col) {
    return col == 0 ? "Text" : "Entered At";
    public boolean isCellEditable(int row, int col) {
    return false;
    }

    fixed my own problem - make your mulit-line string into html format e.g.
    this string will appear on two lines in a jtable
    "<html><p>A much more interesting entry</p> <p>on multiple lines</p></html>"

  • JTable column headers not showing up

    I have a JTable inside a JScrollPane which, in turn, is inside a JTabbedPane.
    I created a TableModel which extends AbstractTableModel as per the java Swing Tutorial examples.
    In that model is an Object[][] object for the data called rowData, and all the data displays in the table perfectly.
    I also have a String[] object called columnNames to define the column headers. ..the column names are coded directly into the object.
    i.e.: String[] columnNames = {"John", "Janet", "Jamie", "Jennifer"};But the column names don't display at all.....all I get in the column headers is 'A', 'B', 'C', etc.
    I need to know either
    1)how to set this up correctly in the first place or
    2)how I can reset the columns manually.
    I have tried adding the table 2 ways..as follows...but neither one gets the headers right:
    JScrollPane jScrollPane = new javax.swing.JScrollPane(getTable());or
    JScrollPane jScrollPane.setViewportView(getTable());Note: getTable()..is where the new javax.swing.JTabel(new TableModel())stuff is done.
    thx, ESW

    You mentioned the you columnNames array. I suggest you declare it as static and accessible from within your custom table modelprivate static final String[] COLUMN_NAMES = {"John", "Janet", "Jamie", "Jennifer"};Then you override/implement the following methods in your TableModel :public String getColumnName(int column) {
         return COLUMN_NAMES[column];
    public int getColumnCount() {
         return COLUMN_NAMES.length;
    }That should do the trick.

  • JTable auto size columns/headers

    How do I autoresize a JTable column/headers so that each column/header is the minium size necessary.
    I've tried setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS); and that doesn't
    seem to work.
    Thanks

    You need to calculate the width of the text and set the preferred size of each column.
    If seen solutions posted in the forum (but no I don't know the exact posting) so you can search the forum to find them.

Maybe you are looking for

  • Transfering music and files from a pc to my mac

    i have music files as well as other files (music the most important) and want to transfer it to my mac. the pc is networked w/ my mac and i can play the files through a shared file...but i want to save the files on to my mac any suggestions any help

  • Oracle Terminal Developer 6.0

    Hello, I want to change the default key binding of "Next Record" to the key "PageDown" ! When i hit the Generate Button i get this error message: Resoure Name: windows-sqlforms Type: bindings. Error while parsing the binding string "PAGEDOWN" of an e

  • Sol 8/9 flars on sol 10 jumpstart

    Our current architecture uses the Solaris 9 Tools/Boot to load out both sol 8 and sol 9 flash archive images. When trying to upgrade to Solaris 10, the sol 8 and 9 archives cause problems. They appear to load out ok, but fsck won't stat the disks. I

  • Oracle AS 10.1.2.3 - Application/Web Service 'not loaded'

    I've successfully deployed my application against OAS 10.1.3.3 with no problems. Unfortunately, my target platform is 10.1.2.3 and I cannot upgrade. When I deploy my application against OAS 10.1.2.3, it does not start/load. When I look at the applica

  • How to post idoc from r/3 to xi

    hi experts i have one doubt abt posting idoc from r/3 to xi how to post for vendor master idoc for sales order idoc for purchase order idoc for delivery idoc          is there any inbuilt posting prgms r there or we have to write the prms. please cle