Initial headers in JTable

Hi
I am having a problem using AbstractTableModel. The thing is that it is working perfectly for my application but I can get the header to appear with the initial names that I am setting. I am following some examples that I found on how to use this class, but in all of them the headers are declared at the begining in an String array;
e.g. String[] headers= {"Last", "Name", "Sex"}
But on the rest of the code I can't find where these values are actually set as headers for the table. When the table is displayed I get "A", "B", and "C" as the headers.
Thanks in advance

Once that you have your clumn names you must to put obn the Model.....
String[] headers= {"Last", "Name", "Sex"}
       // Create a model of the data.
        TableModel dataModel = new AbstractTableModel() {
            public String getColumnName(int column) {return headers[column];} //NOTE THIS ROW...

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.

  • JCheckBox wont receive initial focus in JTable under 1.6

    If I have a JCheckBox in a JTable, clicking the checkbox has no effect unless the table already has focus. This is new to 1.6 I believe.
    The code example below should illustrate the problem. With focus on the JTextField at the top, try to click a checkbox in the table. It won't take respond. If you click another field in the table first, the checkbox will then begin responding. Two strange things I've noticed with it are.
    1) removing the call the table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE); makes it work correctly. Of course then it won't give up focus correctly.
    2) My example has the JTable within a JInternalFrame. If the table is just in a JFrame, the problem disappears. You can commment/uncomment these two lines to see the difference:
    initInteralFrame(panel);
    //initNoInteralFrame(panel);
    I'm very surprised nobody else has noticed this, but I didn't see any postings or bugs on it. Can anyone see something I am doing wrong or find a workaround?
    I submitted this bug a while back which is probably related, but this case with the checkbox is a bit less obscure:
    http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6568959
    import java.awt.Dimension;
    import javax.swing.BoxLayout;
    import javax.swing.JDesktopPane;
    import javax.swing.JFrame;
    import javax.swing.JInternalFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.JTextField;
    import javax.swing.table.DefaultTableModel;
    public class TableTest2 extends JFrame
         public TableTest2()
              addWindowListener(new java.awt.event.WindowAdapter()
                   public void windowClosing(java.awt.event.WindowEvent evt)
                        System.exit(0);
              JPanel panel = new JPanel();
              panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
              String[] columnNames = {"First Name",     "Last Name","Sport","# of Years","Vegetarian"};
              //Object[][] data= new Object[3][5];
              Object[][] data = {
                   {"Mary", "Campione","Snowboarding", new Integer(5), new Boolean(false)},
                   {"Alison", "Huml", "Rowing", new Integer(3), new Boolean(true)},
                   {"Kathy", "Walrath","Knitting", new Integer(2), new Boolean(false)},
                   {"Sharon", "Zakhour","Speed reading", new Integer(20), new Boolean(true)},
                   {"Philip", "Milne","Pool", new Integer(10), new Boolean(false)}
              DefaultTableModel myModel = new DefaultTableModel(data, columnNames)
                   public Class getColumnClass(int c)
                        return getValueAt(0, c).getClass();
              JTable table = new JTable(myModel);
              table.setSurrendersFocusOnKeystroke(true);
              table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
              JScrollPane jScrollPane = new JScrollPane();
              jScrollPane.setViewportView(table);
              panel.add(new JLabel("Field 1"));
              panel.add(new JTextField(15));
              panel.add(jScrollPane);
              // ************ comment out one or the other of these to see error
              initInteralFrame(panel);
              //initNoInteralFrame(panel);
              Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
              setSize(new Dimension(800, 600));
              setLocation((screenSize.width-800)/2,(screenSize.height-600)/2);
         private void initInteralFrame(JPanel panel)
              JInternalFrame jif = new JInternalFrame();
              JDesktopPane desktop = new JDesktopPane();
              jif.setVisible(true);
              desktop.add(jif);
              setContentPane(desktop);
              jif.add(panel);
              jif.pack();
         private void initNoInteralFrame(JPanel panel)
              getContentPane().add(panel);
          * @param args the command line arguments
         public static void main(String args[])
              new TableTest2().setVisible(true);
    }

    It appears to me that the first click is "selecting"
    the internal frame to make it active and therefore
    have focus.Under 1.5, that appears to be the behavior. Under 1.6 the focus starts out in the internal frame on the JTextField above the JTable. You can click into any field in the table from there fine, but you can't transfer focus from the JTextField outside the table to the JCheckbox in the table... no matter how many clicks. The checkbox only works after the table becomes focused by clicking on one of the other fields or tabbing into the table.

  • 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 :)

  • Vertical Headers in JTable

    Anybody ever done something like that ?
    I need to display a very large grid, where the headers have a fairly long text, but each cell only has a single character in it, so I was thinking of making the headers vertical.
    Any help, pointers would be appriciated.

    Actually I am looking for a way to show text on an angle in the header :-)

  • JTable Multi Level Row Headers

    Hi All
    does any one know what's the better way to create MultiLevel Row Headers in JTable.
    for Ex.
    |- Hot
    |- Drinks--------|
    | |- Cold
    Food-------|
    | |- Soft
    | - Fruits-------|
    |- Hard
    and it goes on....to the n level.
    Is there any predefined classes available in Swing for this functionality.
    Thanks in Advance
    Kiran.R

    where did you find this ?
    http://www2.gol.com/users/tame/swing/examples/JTableExamples1.html
    That has some pretty hardcore examples!
    -jonathan

  • JTable  with headers extending JDialog

    I am creating a class file extending JDialog. I have populated the JTable on the form and want to include headers on the table. The dialog form opens and the table is visible and populated but with no headers. Has anyone had success with headers on JTables when creating a JDialog object?
    I have other tables created with headers so I wondered if the problem was with JDialog?

    inorder to make headers visible you need to add scroll pane to table,
    either by:
    JScrollPane scrollPane = JTable.createScrollPaneForTable(table);
    or:
    scrollPane = new JScrollPane(table);
    unless there's no scroller, you can't see headers.

  • JTable  - getting component width

    Hello
    I've come across a small problem I can't overcome as I'm new with Swing.
    I would like to set the initial sizes of JTable column headers using a values from array that indicate the percentage size of JTable container for every header e.i.:
    int[] columnsWidth = new int[]{20,70,5,5};   //4 columns //20%,70%,5%,5% of   JTable width
    //in MyTable constructor
                    TableColumn column = null;
              for(int i =0; i<dm.getColumnCount();i++){
                   column = getColumnModel().getColumn(i);
                      double width = (columnsWidth/100.0)* getWidth();
                   column.setPreferredWidth((int)width);
    unfortunately JComponent:getWidth() returns 0, probably because its in JTable constructor, but where can i get correct component width ?
    Thanks for your help!

    I have some code that does something close; but I don't think it's completely what you want.
    First, in our table model, we define some widths:
    private final static int[] widths = { 10, 20, 20, 10};Then, in our table class, we for each of these columns. We essentially take the width of 10, multiple by some value, and use that value. I was tryign to be able to specify widths in characters, assuming a fixed width font.
        private void setPreferredColumnWidths() {
            for (int i = 0; i < getColumnCount(); i++) {
                TableColumn col = getColumnModel().getColumn(i);
                int w = getColumnWidth(i);
                col.setPreferredWidth(w);
                col.setWidth(w);
        }We disable the resize on the table columns, as we want fixed width columns within a scrollable pane. However, if you enable auto sizing:
    setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);You'll find that the EXTRA space is alloted relative on the preferred size of those columns. It doesn't result in the exact % width you are looking for, so I don't know if that's close enough for you.

  • Shading part of a JTable Cell dependent upon the value of the cell

    Hi
    Was hoping some one woudl be able to provide some help with this. I'm trying to create a renderer that will "shade" part of a JTable cell's background depending upon the value in the cell as a percentage (E.g. if the cell contains 0.25 then a quarter of the cell background will be shaded)
    What I've got so far is a renderer which will draw a rectangle whose width is the relevant percentage of the cell's width. (i.e. the width of the column) based on something similar I found in the forum but the part I'm struggling with is getting it to draw this rectangle in any cell other than the first cell. I've tried using .getCellRect(...) to get the x and y position of the cell to draw the rectangle but I still can't make it work.
    The code for my renderer as it stands is:
    import java.awt.Component;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import javax.swing.JLabel;
    import javax.swing.JTable;
    import javax.swing.table.TableCellRenderer;
    public class PercentageRepresentationRenderer extends JLabel implements TableCellRenderer{
         double percentageValue;
         double rectWidth;
         double rectHeight;
         JTable table;
         int row;
         int column;
         int x;
         int y;
         public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
              if (value instanceof Number)
                   this.table = table;
                   this.row = row;
                   this.column = column;
                   Number numValue = (Number)value;
                   percentageValue = numValue.doubleValue();
                   rectHeight = table.getRowHeight(row);
                   rectWidth = percentageValue * table.getColumnModel().getColumn(column).getWidth();
              return this;
         public void paintComponent(Graphics g) {
            x = table.getCellRect(row, column, false).x;
            y = table.getCellRect(row, column, false).y;
              setOpaque(false);
            Graphics2D g2d = (Graphics2D)g;
            g2d.fillRect(x,y, new Double(rectWidth).intValue(), new Double(rectHeight).intValue());
            super.paintComponent(g);
    }and the following code produces a runnable example:
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.DefaultTableModel;
    public class PercentageTestTable extends JFrame {
         public PercentageTestTable()
              Object[] columnNames = new Object[]{"A","B"};
              Object[][] tableData = new Object[][]{{0.25,0.5},{0.75,1.0}};
              DefaultTableModel testModel = new DefaultTableModel(tableData,columnNames);
              JTable test = new JTable(testModel);
              test.setDefaultRenderer(Object.class, new PercentageRepresentationRenderer());
              JScrollPane scroll = new JScrollPane();
              scroll.getViewport().add(test);
              add(scroll);
         public static void main(String[] args)
              PercentageTestTable testTable = new PercentageTestTable();
              testTable.pack();
              testTable.setVisible(true);
              testTable.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }If anyone could help or point me in the right direction, I'd appreciate it.
    Ruanae

    This is an example I published some while ago -
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class Fred120 extends JPanel
        static final Object[][] tableData =
            {1, new Double(10.0)},
            {2, new Double(20.0)},
            {3, new Double(50.0)},
            {4, new Double(10.0)},
            {5, new Double(95.0)},
            {6, new Double(60.0)},
        static final Object[] headers =
            "One",
            "Two",
        public Fred120() throws Exception
            super(new BorderLayout());
            final DefaultTableModel model = new DefaultTableModel(tableData, headers);
            final JTable table = new JTable(model);
            table.getColumnModel().getColumn(1).setCellRenderer( new LocalCellRenderer(120.0));
            add(table);
            add(table.getTableHeader(), BorderLayout.NORTH);
        public class LocalCellRenderer extends DefaultTableCellRenderer
            private double v = 0.0;
            private double maxV;
            private final JPanel renderer = new JPanel(new GridLayout(1,0))
                public void paintComponent(Graphics g)
                    super.paintComponent(g);
                    g.setColor(Color.CYAN);
                    int w = (int)(getWidth() * v / maxV + 0.5);
                    int h = getHeight();
                    g.fillRect(0, 0, w, h);
                    g.drawRect(0, 0, w, h);
            private LocalCellRenderer(double maxV)
                this.maxV = maxV;
                renderer.add(this);
                renderer.setOpaque(true);
                renderer.setBackground(Color.YELLOW);
                renderer.setBorder(null);
                setOpaque(false);
                setHorizontalAlignment(JLabel.CENTER);
            public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col)
                final JLabel label = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);
                if (value instanceof Double)
                    v = ((Double)value).doubleValue();
                return renderer;
        public static void main(String[] args) throws Exception
            final JFrame frame = new JFrame("Fred120");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setContentPane(new Fred120());
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
    }

  • JTable and ResultSet TableModel with big resultset

    Hi, I have a question about JTable and a ResultSet TableModel.
    I have to develop a swing JTable application that gets the data from a ResultSetTableModel where the user can update the jtable data.
    The problem is the following:
    the JTable have to contain the whole data of the source database table. Currently I have defined a
    a TYPE_SCROLL_SENSITIVE & CONCUR_UPDATABLE statement.
    The problem is that when I execute the query the whole ResultSet is "downloaded" on the client side application (my jtable) and I could receive (with big resultsets) an "out of memory error"...
    I have investigate about the possibility of load (in the client side) only a small subset of the resultset but with no luck. In the maling lists I see that the only way to load the resultset incrementally is to define a forward only resultset with autocommit off, and using setFetchSize(...). But this solution doesn't solve my problem because if the user scrolls the entire table, the whole resultset will be downloaded...
    In my opinion, there is only one solution:
    - create a small JTable "cache structure" and update the structure with "remote calls" to the server ...
    in other words I have to define on the server side a "servlet environment" that queries the database, creates the resultset and gives to the jtable only the data subsets that it needs... (alternatively I could define an RMI client/server distribuited applications...)
    This is my solution, somebody can help me?
    Are there others solutions for my problem?
    Thanks in advance,
    Stefano

    The database table currently is about 80000 rows but the next year will be 200000 and so on ...
    I know that excel has this limit but my JTable have to display more data than a simple excel work sheet.
    I explain in more detail my solution:
    whith a distribuited TableModel the whole tablemodel data are on the server side and not on the client (jtable).
    The local JTable TableModel gets the values from a local (limited, 1000rows for example) structure, and when the user scroll up and down the jtable the TableModel updates this structure...
    For example: initially the local JTable structure contains the rows from 0 to 1000;
    the user scroll down, when the cell 800 (for example) have to be displayed the method:
    getValueAt(800,...)
    is called.
    This method will update the table structure. Now, for example, the table structure will contain data for example from row 500 to row 1500 (the data from 0 to 499 are deleted)
    In this way the local table model dimension will be indipendent from the real database table dimension ...
    I hope that my solution is more clear now...
    under these conditions the only solutions that can work have to implement a local tablemodel with limited dimension...
    Another solution without servlet and rmi that I have found is the following:
    update the local limited tablemodel structure quering the database server with select .... limit ... offset
    but, the select ... limit ... offset is very dangerous when the offset is high because the database server have to do a sequential scan of all previuous records ...
    with servlet (or RMI) solution instead, the entire resultset is on the server and I have only to request the data from the current resultset from row N to row N+1000 without no queries...
    Thanks

  • JTable problem

    I'm writing an application that will display info in multiple tables. I thought it would be a good idea to write my own table class. The problem is that only the table data appears, but not the table headers.
    Layout.java creates an object of MyTable.java. The "createTable" constructor returns a JPanel wich in turn contains a JTable.
    Layout.java (creates the GUI, extends JFrame)
        String[] headers = {"1","2","3","4","5","6"};
        String[][] data = {{"one","two","three","four","five","six"},{"seven","eight","nine","ten","eleven","twelve"}};
        MyTable jt = new MyTable();
        Component table = jt.createTable(data, headers);
        JScrollPane jsp = new JScrollPane(table);
        getContentPane().add(jsp, BorderLayout.CENTER);
    MyTable.javapublic Component createTable(String[][] d, String[] h)
        data = d;
        headers = h;
        JPanel contentPane = new JPanel();
        TableModel tm = new AbstractTableModel(){
         public int getRowCount(){return data.length;}
         public int getColumnCount() {return headers.length;}
         public Object getValueAt(int r, int c) {return data[r][c];}
              public String getColumnName(int c) {return headers[c];}
        JTable jt = new JTable(tm);
        jt.setMaximumSize(new Dimension(700,40));
        jt.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        contentPane.add(jt);
        return contentPane;
    }

    The table headers are not really part of the table, they are a separate component.
    Normally a JTable is added directly to a JScrollPane. The JScrollPane is smart enough to take the column information create a component and add this component to the JScrollPane using the setColumnHeaderView() method of JScrollPane.
    In your example you are adding the JTable to a Component and then adding the Component to a JScrollPane so the headers don't get created.
    I suggest you add your table to the scrollpane in your createTable() method.

  • Please help with Database and JTable.

    The class listed below is for a JTable. The main in this class is for testing only, when complete main will reside elsewhere. I need to know how to make this JTable universal. How can I set it up so that when called in a main and passed parameters it will display the information contained in that users database?? Again it must be universal so no matter who uses it, it will perform the same on all database's.
    Here's the code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class DisplayTable extends JFrame{
    public DisplayTable() {
         JFrame jf = new JFrame("Window Title");
              jf.setSize(1100,700);
              jf.setLocation(25,50);
              jf.addWindowListener(new WindowAdapter(){
                   public void windowClosing(WindowEvent e){
                        System.exit(0);}
         TableModel tm = new AbstractTableModel(){
              String[][] data = { {"How to get database data??"}};
              String[] headers = {"How to get database headers??"};
              public int getRowCount() {return data.length;}
              public int getColumnCount() {return headers.length;}
              public Object getValueAt(int r, int c) {return data[r][c];}
              public String getColumnName(int c) {return headers[c];}
         JTable jt = new JTable(tm);
         JScrollPane jsp = new JScrollPane(jt);
              jf.getContentPane().add(jsp, BorderLayout.CENTER);
              jf.setVisible(true);
    public static void main(String args[]){
         DisplayTable dt = new DisplayTable(Database Parameters to be given here);

    You could generalize it, but it gets tricky to deal with the data types and if the JTable is editable because you would read the DB table data at run time. Using the ResultSetMetaData, you would be able to find the column type too. But, how can we cast an object at run-time?
    Below, I have provided an overview as of doing a read-only (all-strings version) of it. You may have some ideas from there.
    The database parameters that you pass to the constructor would tell the model where to connect and which DB table to read the data from. Couple of options:
    1. You can read the data in the constructor of DisplayTable into final variables and have the inner class (model) set its data and headers from those variables.
    Or
    2. Pull out the model as a separate class extending AbstractTableMode. Doing this, you can pass on the DB information to the model and have the model talk to the DB.
    And, I would use dynamic datastructures like Vector or List instead of arrays.
    You would have the following logic wherever you chose to talk to the DB:
    I am assuming that you are trying to read a complete DB table into your JTable (or may be you would pass a SELECT-query alongwith your DB information). Whatever may be the case, you would execute a select- to the DB and get a resultset back. Using that you would be able to get the ResultSetMetaData, which will give you the column count and column names. You may chose to use these column names as the header names for your JTable. With the column count you would query every row to get the object at each column.
    Here is a sample model:
    class MyModel extends AbstractTableModel {
        ArrayList columnNames = new ArrayList();
        ArrayList data = new ArrayList();
        MyModel(<DB Info>) {
            // Use the DB info and get the resultset
            ResultSetMetaData rsm = rs.getMetaData();
            int col = rsm.getColumnCount();
            for(int i=1; i<=col; i++) {
                columnNames.add(rsm.getColumnName(i));
            // Read the data
            while(rs.next()) {
                ArrayList row = new ArrayList();
                data.add(row);
                for(int j=1; j<=col; j++) {
                    // Here is the tricky part which I did not figure yet. For now, I am reading in all as Strings.
                    row.add(rs.getObject(j).toString());
        public String getColumnName(int c) {
            return (String)columnNames.get(c);
        public int getColumnCount() {
            return columnNames.size();
        public Object getValueAt(int r,int c) {
            ArrayList row = (ArrayList)data.get(r);
            return (String)row.get(c);
        public int getRowCount() {
            return data.size();
    }If you figured a way to handle run-time casting, please let us know.
    HTH.
    Vijay

  • Multi line headers

    Does anyone know how to have multiple line headers in JTable?

    Most components except can render HTML text. A header in a JTable is one of them. Try:
    String header = "<html>line 1<br>line 2</html>";

Maybe you are looking for

  • How I fixed my short battery life on iPhone 5, and ActiveSync problems at the same time.

    For anyone still having activesync or battery problems I have a potential fix: I've had two issues lately.  First, my battery life was draining at an insane rate.  iPhone5 lasted about 3-4 hours before absolutely dead from a full charge.  LTE disable

  • Problem with Pages Palette CS2

    I am missing a scroll bar and my dup. and trash buttons. ALSO it pushes all my pages so i cant even see them.. What could of happened to do this.. i am not even sure if it was ever correct.. this is a work program and it was installed last year by a

  • AP On Different Vlan Than Controller

    I have a 5508 controller at our headquarters and am installing some 3502 AP's at a remote branch.  Unfortunatly, the remote branch has a different Vlan setup for some reason and the vlan that is used for the WLC (90) is designated for telephony at th

  • Problem with the External send output for Portugal in Smartforms

    Hello All, I am facing an issue with a particular outtype for external send for portugal country.The print priview is of different font than original font of the form. But When the same output type is assigned with the print output the form is showin

  • Which USB B/W laser with intel drivers?

    Just looking to get a small USB B/W laser printer, trying to work out which one has 10.4.9 and intel drivers for my MacBook? Can someone recomend one that they are using. The Brother HL-2040 or Samsung ML-2510 looks good but seems to be using a CUPs