Jtable (in Jscrollpane) headers missing????

hello,
i need to show the results of a resultset in a jtable. i am putting the table in a jscrollpane... but still the headers dont show up. i have tested the array "headers" (Object[] headers) and is full with the correct data.
what is missing??
JTable table = new JTable(data,headers);
        table.setSize(jScrollPaneResultados.getSize());
        jScrollPaneResultados.add(table);
        table.setFillsViewportHeight(true);thank�s

The scrollPane.add(...) method doesn't work the way you expect it to.
You can use the setViewportView(...) method, or you can read the JTable API for an example of adding a table to the scrollpane when the scrollpane is created.

Similar Messages

  • 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.

  • Mouse motion listener for JTable with JScrollpane

    Hi All,
    I have added mouse motion listener for JTable which is added in JScrollPane. But if i move the mouse, over the vertical/horizontal scroll bars, mouse motion listener doesn't works.
    So it it required to add mousemotionlistener for JTable, JScrollPane, JScrollBar and etc.
    Thanks in advance.
    Regards,
    Tamizhan

    I am having one popup window which shows address information. This window contains JTable with JScrollPane and JButton components to show the details. While showing this information window, if the mouse cursor is over popupwindow, it should show the window otherwise it should hide the window after 30 seconds.
    To achieve this, i have added mouse listener to JPanel, JTable, JButton and JScrollPane. so if the cursor is in any one of the component, it will not hide the window.
    but for this i need to add listener to all the components in the JPanel. For JScrollPane i have to add horizontal, vertical and all the top corner buttons of Scroll bar.
    Is this the only way to do this?

  • 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 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 update, column headers

    I am trying to write my own tablemodel which does not change the specified
    column widths when updating. So far everthing works fine, only the column
    headers are not repainted. Does anybody know what is missing?
    import java.awt.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    public class UpdateTable
    { static String headers[]= {"Baum", "Blatt", "Frucht","H�usigkeit"};;
      static String data[][]= {
         {"Eiche", "gez�hnt","Eichel","ein"},
         {"Buche", "glatt", "Buchecker","ein"},
         {"Tanne", "Nadel", "Zapfen","ein"},
         {"Pappel", "wechselst�ndig","Kapsel","zwei"},
      static MyTableModel tblModel;
      static JTable table;
      public UpdateTable()
      { JFrame frame = new JFrame("UpdateTable");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container contentPane = frame.getContentPane();
        tblModel = new MyTableModel(data, headers)
        { // Make read-only
          public boolean isCellEditable(int x, int y)
          { return false;
        table = new JTable(tblModel);
        table.getColumnModel().getColumn(1).setPreferredWidth(200);
        table.getColumnModel().getColumn(3).setPreferredWidth(20);
          // Set selection to first row
        ListSelectionModel selectionModel = table.getSelectionModel();
        selectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        selectionModel.addListSelectionListener (new ListSelectionListener()
        { public void valueChanged(javax.swing.event.ListSelectionEvent e)
            if (e.getValueIsAdjusting()) return;
                System.out.println(table.getSelectedRow());
          // Add to screen so scrollable
        JScrollPane scrollPane = new JScrollPane (table);
        contentPane.add(scrollPane, BorderLayout.CENTER);
        frame.setSize(500, 100);
        frame.setVisible(true);
      public static void main(String args[])
      { new UpdateTable();
        try
        { Thread.sleep(3000);
        catch (InterruptedException e)
        { System.out.println ("Fehler: "+ e.toString());
        String headers_neu[] = {"Arbre", "Feuille", "Fruit", "Maisonette"};
        headers = headers_neu;
        data[0][0]= "Eberesche";
        tblModel.setDataVector(data, headers);
    //    table.revalidate(); // is of no use.
        table.repaint();
    // The table model
    class MyTableModel extends AbstractTableModel
      private int cols, rows;
      private String[] columnNames;
      private String[][] data;
      public MyTableModel(int cols, int rows)
      { this.cols = cols;
        this.rows = rows;
      public MyTableModel(String[][] data, String[] columnNames)
      { setDataVector(data, columnNames);
      public String getColumnName(int col)
      { return columnNames[col].toString();
      public int getColumnCount()
      { return cols;
      public int getRowCount()
      { return rows;
      public Object getValueAt(int row, int col)
      { return data[row][col];
      public void setDataVector(String[][] data, String[] columnNames)
      { this.cols = data[0].length;
        this.rows = data.length;
        this.data= data;
        this.columnNames= columnNames;
    //    Firing the event will change column widths as usual.
    //    fireTableChanged(new TableModelEvent(this,TableModelEvent.HEADER_ROW););
    }

    // fireTableChanged(new TableModelEvent(this,TableModelEvent.HEADER_ROW););
    You have to fire a table changed event.
    The table neverasks the model if things have changed. The model always notifys the table of changes.
    No event fired no table repaint.
    Instead of fireTableChanged(...) you have the option of fireTableDataChanged() (if only the data has changed, not the nomber of columns or the type of columns) and fireTableStructureChanged() (if there have been columns changed).
    If fireTableStructureChanged happens (and HEADER_ROW event is the same thing), the table removes the columns and creates new onew. That's why column sizes are lost.
    If you really want the table not to manage columns, you have to do it yourself:
    Implement your own TableColumnModel and pass it to the table constructor. When adding/removing columns you can ask what was the size of the previous columns where and set the new columns to that size.
    Call setAutoCreateColumnsFromModel(false) in your table constructor so that the table will not remove/create new columns itself when a tableStructureChanged event happens.

  • Print JTable with row headers

    I am using the fancy new printing capablities in java 1.5 to print my JTable and wow is it ever slick!
    PrintRequestAttributeSet set = new HashPrintRequestAttributeSet();
    set.add(OrientationRequested.LANDSCAPE);
    this.matrixJTable.print(JTable.PrintMode.NORMAL, null, null, true, set, false);Its just that easy. Way to go sun!
    The one problem that I am encountering is that my row headers don't print. The problem is that JTables don't support row headers, you have to use a JScrollPane for that.
    I need a way to print my JTable so that the row headers show up in the printout... and hopefully still use the warm and fuzzy new printing capabilities of JTable printing in java 1.5.
    (ps/ Isn't it time to add row header support to JTables?)

    The problem is that JTables don't support row headers, you have to use a JScrollPane for that.Well technically JTable's don't really support column headers either. It is a seperate component (JTableHeader). A JTable will automatically add its table header to the table header area of a JScrollPane. (but you don't have to use a jscrollpane to see the column headers, it is just the quickest and easiest way).
    Really shouldn't be hard to implement a row header and manually add it to the scroll panes row header area or use a BorderLayout and put your row header in the WEST and put your table in the CENTER if you don't want a scroll pane.
    Of course this won't help you with your printing issue.

  • JTable without column headers?

    I want a JTable without the column headers.
    How can i do this?
    Cheers?

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Test extends JFrame {
        public Test() {
         String[] head = {"","",""};
         String[][] data = {{"0-0","0-1","0-2"},
                       {"1-0","1-1","1-2"},
                       {"2-0","2-1","2-2"}};
         JTable myTable = new JTable(data,head);
         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         Container content = getContentPane();
         content.add(new JScrollPane(myTable), BorderLayout.CENTER);
         setSize(200,200);
         show();
        public static void main(String[] args) { new Test(); }
    }

  • JTable column-spanning headers

    It there a neat way of creating an equivalent of the HTML colspan effect in JTables, particularly in the headers?
    I want to produce a table with headers divided into major and minor categories.
    I guess I can write my own extension of JTableHeader, but that's going to get messy.

    For the benefit of anyone searching for a solution.
    I've found a way of doing this that isn't too much hastle. I create a secondary DefaultTableColumnModel and add columns initialised to the combined width of the groups of columns in the table's TableColumnMode which the more generic headers corespond to. Column reordering is disabled on both models and width changes on the extra one.
    Based on this I create a JTableHeader component which I juxtapose with the table and main header using a Box.
    I add a TableColumnModelListener to the original ColumnModel. the columnMarginsChanged method causes all the widths in the secondary column model to be recalculated from the original.
    The only problem I've had is to persuade the new JColumnHeader to addopt a sensible size. I've had to set both minimum and maximum dimensions before the display will layout properly.
    Haven't tried this with a JScrollPane yet but you should be able to bolt the two headers together and stick them in the header slot of the scrollpane.

  • How to display column header of a JTable in JScrollpane's RowHeader

    Can anyone tell me if it's possible to display the colum headers of a JTable which acts as the row headers of a JScrollpane object?
    If the answer is yes, could he/she point me to the right direction?
    Thanks,

    I'm guessing the answer is no because the column header is layed out horizontally and a row header is layed out vertically. But it should be easy enough to test:
    scrollPane.setRowHeaderView(table.getTableHeader());
    Its not hard to create your own row header. Search the forum using "+setrowheaderview +camickr" to find examples I've posted.

  • JTable in JScrollpane doesn't appear

    Hi,
    Maybe, it's already asked 1000 times on this forum but I didn't found the right solution.
    My problem :
    I've created a JPanel with a JScrollpane.
    When I create the JScrollpane immediately with a JTable it works fine, the JTable appears.
    Now I try to add the JTable dynamically to the JScrollpane.
    The JTable doesn't appear.
    I've tried already the repaint, validate methods but that changes nothing.
    Can anyone tell me how I can solve my problem ?
    Thanx in advance,
    Piet

    I trust you are adding it like this:
    myJScrollPane.getViewport().add(myJTable);
    not like this:
    myJScrollPane.add(myJTable);

  • JTable in JScrollPane auto resize refresh problem

    Hello,
    I have a JTable in a JScrollPane. Number of rows is changing.
    I'm using the following to auto-resize JScrollPane.
    public Dimension getPreferredSize() {
                  Dimension size = super.getPreferredSize();
                  size.height -= getViewport().getPreferredSize().height;
                  Component view = getViewport().getView();
                  if(view != null)
                  size.height += view.getPreferredSize().height;
                  return size;
             }There is a JButton, which adds an empty row to the JTable. It all works fine, except the auto-resize when a new row is added. I want all rows of JTable to be visible, with no scrollbars present. I tried repaint(), revalidate(), addNotify(). What should I do?
    Thanks.

    Sure
    DefaultTableModel dtm = new DefaultTableModel(vec, header);
              jt0 = new JTable(dtm);
              jt0.getTableHeader().setReorderingAllowed(false);
              jt0.setFont(new Font("Tahoma", Font.PLAIN, 12));
              jt0.getTableHeader().setFont(new java.awt.Font("Tahoma", java.awt.Font.BOLD, 12));
              jt0.setRowHeight(18);
            jt0.setPreferredScrollableViewportSize(new Dimension(500, jt0.getRowCount() * jt0.getRowHeight()));
            jt0.setFillsViewportHeight(false);
              jsp0 = new JScrollPane(jt0);
    GridBagConstraints gbc = new GridBagConstraints(); 
            gbc.insets = new Insets(2,1,2,1); 
            gbc.weightx = 1.0; 
            gbc.weighty = 1.0; 
            JPanel p0 = new JPanel(new GridBagLayout()); 
            gbc.fill = gbc.HORIZONTAL;
            p0.add(jsp0, gbc);
              JButton jb1 = new JButton("add row");
              jb1.setSize(40, 18);
    jb1.addActionListener(new java.awt.event.ActionListener() {
                   public void actionPerformed(java.awt.event.ActionEvent e) {
                        dtm.addRow(new Object[]{....});
    //                    jt0.scrollRectToVisible(jt0.getCellRect(jt0.getModel().getRowCount()-1, 1, false));
    //                    jt0.setRowSelectionInterval(jt0.getModel().getRowCount()-1, jt0.getModel().getRowCount()-1);
        public class SizeX extends JScrollPane {
             public Dimension getPreferredSize() {
                  Dimension size = super.getPreferredSize();
                  size.height -= getViewport().getPreferredSize().height;
                  Component view = getViewport().getView();
                  if(view != null)
                  size.height += view.getPreferredSize().height;
                  return size;
        }

  • Resize jtable in jscrollpane

    Hi,
    I have a frame containing a JTable and a panel with buttons. When the window gets resized, I would like that the jtable takes the extra space and that the button panel stays the same. How can I do that? The jtable panel is already the "Center" and both panels stay the same...
    Thanks,
    Marie
    Here's the code:
    package test;
    import javax.swing.*;
    import java.awt.AWTEvent;
    import java.awt.event.WindowEvent;
    import java.awt.BorderLayout;
    import java.awt.GridLayout;
    import javax.swing.table.TableColumn;
    import javax.swing.table.TableColumnModel;
    public class Testframe extends JFrame {
        private JPanel mainPanel = new JPanel();
        private JPanel buttonPanel = new JPanel();
        private JPanel tablePanel = new JPanel();
        //Button panel
        private JButton applyTableBt = new JButton("Generate Table");
        private JButton addBt = new JButton("Add");
        private JButton editBt = new JButton("Edit");
        private JButton deleteBt = new JButton("Delete");
        private JButton matchBt = new JButton("Find");
        private JButton saveBt = new JButton("Save to file");
        private JButton loadBt = new JButton("Load from file");
         * Constructor.
         * @param a_parent Frame
        protected Testframe() {
            enableEvents(AWTEvent.WINDOW_EVENT_MASK);
            try {
                jbInit();
                this.setResizable(true);
                this.setVisible(true);
                pack();
            } catch (Exception e) {
                e.printStackTrace();
         * Initialization of the dialog.
         * @throws Exception
        private void jbInit() throws Exception {
            this.setTitle("Pattern management - CAT");
            Object[][] data = { {"11", "12", "13", "14", "15", "16", "17", "18"},
                              {"21", "22", "23", "24", "25", "26", "27", "28"}
            Object[] names = {"col1", "col2", "col3", "col4", "col5", "col6",
                             "col7", "col8"};
            JTable table = new JTable(data, names);
            table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
            //table.setColu
            TableColumnModel colModel = table.getColumnModel();
            for (int i = 0; i < table.getColumnCount(); i++) {
                TableColumn column = colModel.getColumn(i);
                column.setPreferredWidth(511);
            JScrollPane scrollPane = new JScrollPane(table);
            tablePanel.add(scrollPane);
            //Layout = vertical box with vertical gap
            buttonPanel.setLayout(new GridLayout(7, 1, 0, 5));
            buttonPanel.add(applyTableBt);
            buttonPanel.add(addBt);
            buttonPanel.add(editBt);
            buttonPanel.add(deleteBt);
            buttonPanel.add(matchBt);
            buttonPanel.add(saveBt);
            buttonPanel.add(loadBt);
            //mainPanel.setLayout(new BorderLayout());
            mainPanel.add(tablePanel, BorderLayout.CENTER);
            mainPanel.add(buttonPanel, BorderLayout.EAST);
            this.setContentPane(mainPanel);
         * Overrides this class to call the good method when the dialog is closed.
         * @param a_windowE WindowEvent
        protected void processWindowEvent(WindowEvent a_windowE) {
            //If it is a request to close the window (X)
            if (a_windowE.getID() == WindowEvent.WINDOW_CLOSING) {
                cancel();
            super.processWindowEvent(a_windowE);
         * Closes the dialog.
        private void cancel() {
            dispose();
        private static void createAndDisplayFrame() {
            //Make sure we have nice window decorations.
            JFrame.setDefaultLookAndFeelDecorated(true);
            new Testframe();
        public static void main(String[] args) {
            createAndDisplayFrame();
    }

    try changing these lines
    mainPanel.add(tablePanel, BorderLayout.CENTER);
    mainPanel.add(buttonPanel, BorderLayout.EAST);
    this.setContentPane(mainPanel);
    to this
    mainPanel.add(buttonPanel, BorderLayout.EAST);
    getContentPane().add(scrollPane, BorderLayout.CENTER);
    getContentPane().add(mainPanel, BorderLayout.EAST);

  • JTable in jScrollPane

    Hello, I am developing an application in Netbeans (Swing) with JDBC to connect mySQL. I got a question about a jTable in a jScrollPane. I read from my database and put the resultSet into a dinamical jTable. In the same form, I got a jTextField, where the user can input a code or a name to search in the jTable. When I find the code in the jTable I can select the row to remark the result. The problem I got is when the found code is not showing in the view of the table. So what I want to do, if it is possible, is automatically move the scroll to show the row I have selected; this way, the user don't have to move the scroll along the table (which could have a lot of rows). I have thought another solution could be show another frame with the data of selected row, but I want to try the first one.
    If you know how can I do this please, help me.
    I am sorry if my english is not very well. I hope you can understand my question.
    Thanks

    scphan wrote:
    BigDaddyLoveHandles wrote:
    JScrollPane scroll = new JScrollPane(new JTable(...));
    or scroll.getViewport().setView( new JTable(...) );(no difference implied)So do it the simpler way.

  • JTable in JScrollPane, preferred size

    When I put a JTable in a JScrollPane, the JScrollPane seems to want to be very big. How does the scroll pane determine its size? run this code for an example..
    import javax.swing.*;
    public class TestPanel extends JPanel
    public TestPanel()
         add(new JScrollPane(new JTable(1,1)));
    public static void main(String args[])
         JFrame f = new JFrame("big table test");
         f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         TestPanel thePanel = new TestPanel();
         f.setContentPane(thePanel);
         f.pack();
         f.show();

    public class TestPanel extends JPanel {
      public TestPanel() {
        JTable jt = new JTable(1,1);
        jt.setPreferredScrollableViewportSize(new Dimension(100,100));  // Do this
        JScrollPane jsp = new JScrollPane(jt);
        jsp.setPreferredSize(new Dimension(100,100));  //OR this
        add(new JScrollPane(new JTable(1,1)));
    }

Maybe you are looking for

  • How do I get FaceTime for Mac to stop ringing after answering an incoming call on my iPhone?

    I have iPhone Cellular Calls enabled for iPhone and FaceTime and am able to make and receive calls splendidly with FaceTime. However, when I answer an incoming call on my iPhone, FaceTime will not stop ringing. This is a significant, loud, annoying i

  • Error while publishing a report as a PDF file

    Hi , I am using Bex broadcaster to publish a BI report into a KM folder of Enterprise Portal . I  could do it using mhtml , html formats . If i try using pdf format , it throws a error -  com.sap.ip.bi.base.exception.BIBaseRuntimeException . From wha

  • "Page View"?

    I like Pages, but the biggest obstacle for me to contemplate a serious switch is the look of the window. In Word, there's a "Page View" option that creates gray space around the workspace when you have the window open beyond a certain point. That phy

  • Changing the outbound Mail server?

    Are we able to change the outbound mail server in iphone 3GS? Currently I have Mobileme IMAP on my mac but all the mail is filtered via gmail. On my mac I have the ability to change the outgoing mail so that it looks like I am sending from gmail. On

  • About web service transaction

    Hello everyone: I am a newcomer to web service, but now I have to simulate ws-businessactivity protocol. I don't have any idea about it and where to begin with. I made an survey about JTA and JTS, but it seems this api only supports ws-atomic transac