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.

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

  • 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)));
    }

  • How to retrieve JTable from JScrollPane?

    In the main class MyReconcile which extends JFrame, I have codes as every body do
    myContainer.add(myControlPane, Layout.North);
    myTable = new JTable(dataValues, columnNames );
    myPane = new JScrollPane(myTable);
    myContainer.add(myPane, Layout.Center);
    In another class MyControlPanel, I pass myContainer into this class and try to get that table object, finally I need its data. my code is
    1. thePane = (JScrollPane) theContainer.getComponent(1);
    2. theTable = (JTable) thePane.getComponent(0);
    the result is that 1 is successful, but 2 failed.
    Anybody could give help? Thanks!
    Victor

    I've never done this but you might try:
    theTable = (JTable) thePane.getViewport().getView();

  • JTable without JScrollPane behavior crippled

    I want column width of JTable t1 goes parallel with the width resizing on
    JTable t2. If tables are put in JScrollPanes, this has no problem. But if I put
    those tables in simpler container, which is JPanel in this case, t2 shows a
    funny behavior -- with user's mouse operation on t2 column, their width
    never changes but t1 column width changes properly. Could I have
    succeeded in communicating the funniness with these sentences?
    Please try this code and give cause and solution if you could:
    import java.awt.*;
    import java.beans.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.event.*;
    public class TableColumnWidthResize{
      JFrame frame;
      JTable t1, t2;
      TableColumnModel tcm1, tcm2;
      Enumeration columns1, columns2;
      String[] t1h = {"Road", "Length", "City"};
      String[][] t1c
       = {{"NW2", "800", "Dora"},
         {"Iban", "600", "Weiho"},
         {"ENE2", "500","Porso"}};
      String[] t2h = {"Flower", "Curse", "Priest"};
      String[][] t2c
        = {{"Fang", "7.00", "EggChar"},
          {"Shaoma", "5.00", "ScaCra"},
          {"Jiao", "4.00", "PorCabb"}};
      public TableColumnWidthResize(){
        frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container con = frame.getContentPane();
        con.setLayout(new GridLayout(2, 1));
        t1 = new JTable(t1c, t1h); //target table -- 'resized from t2'
        t2 = new JTable(t2c, t2h); //source table -- 'initiate resize'
        t1.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        t2.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        /* you can compare two methods of table placement*/
        useScrollPane(t1, t2, con); //works fine
    //    nouseScrollPane(t1, t2, con); //resize behavior weird
        frame.pack();
        frame.setVisible(true);
        tcm1 = t1.getColumnModel();
        tcm2 = t2.getColumnModel();
        columns2 = tcm2.getColumns(); // all columns of t2
        TableColumnListener tcl = new TableColumnListener();
        while (columns2.hasMoreElements()){
          TableColumn tc = (TableColumn)(columns2.nextElement());
          tc.addPropertyChangeListener(tcl);
      class TableColumnListener implements PropertyChangeListener{
        // achieve 'interlocking-column-resizing' from t2 to t1
        public void propertyChange(PropertyChangeEvent pce){
          TableColumn tc = (TableColumn)(pce.getSource());
          int i = tc.getModelIndex();
          tcm1.getColumn(i).setPreferredWidth(tc.getWidth());
      void useScrollPane(JTable ta, JTable tb, Container c){
        JScrollPane jsc1 = new JScrollPane(ta);
        ta.setPreferredScrollableViewportSize(new Dimension(225, 50));
        JScrollPane jsc2 = new JScrollPane(tb);
        tb.setPreferredScrollableViewportSize(new Dimension(225, 50));
        c.add(jsc1); c.add(jsc2);
      void nouseScrollPane(JTable ta, JTable tb, Container c){
        JPanel p1 = new JPanel(); JPanel p2 = new JPanel();
        p1.setLayout(new BorderLayout());
        p2.setLayout(new BorderLayout());
        p1.add(ta.getTableHeader(), BorderLayout.PAGE_START);
        p2.add(tb.getTableHeader(), BorderLayout.PAGE_START);
        p1.add(ta, BorderLayout.CENTER);
        p2.add(tb, BorderLayout.CENTER);   
        c.add(p1); c.add(p2);
      public static void main(String[] args){
        new TableColumnWidthResize();
    }

    Hey hiwa,
    I don't see anything mysterious going on. If you think about it, how many components can we resize at run-time/dynamically with a mouse - none, except for the columns in a JTable, Frames and Dialogs. Note the latter two are top level and answer to no-one (except the screen i guess).
    If you have ever implemented a component that can be 'dragged' and manipulated by the mouse, have you ever done so outside, that is, not using a JScrollPane? I doubt it.
    I do not think it has anything to do with mouse precision. Maybe you are just experiencing undefined behaviour, unreliable behaviour. I imagine the Swing team didn't bother themselves with a usage scenario that would yield lesser results for a simple task. Using AUTO_RESIZE_OFF and requesting more room than the Container has to offer may upset that containers LayoutManager i.e. their algorithms may contain code that will shrink child components to fit, or nab space from sibling components.
    Basically, in my experience, how ever long it takes me to realise it, when Swing goes on the blink it is usually a programming error.
    BTW, did my suggestion work ok?
    Sorry if I come across forceful. I'm glad I read and tested your code - the synchronization effect will be very useful.
    Warm regards,
    Darren

  • Jtable on JScrollPane get corrupted for large number of rows

    Hi I have problem with vertical scroll bars of JScrollPane.
    When move the scroll bar(faster) for a Jtable (with 2000 rows) the rows get
    corupted.
    Please let me know how can I fix this problem?

    Hi,
    I have just recompiled my (previously 1.3.1) application with 1.4.2 and notice the same problem. The problem starts somewhere between 1700 and 2500 rows.
    Its not just the scroll bar for me - the display corrupts whereever i click the mouse on the table area.
    Did you manage to diagnose??
    Thanks, Dave

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

  • Is it possible to buffer the entire JTable for JScrollPane scrolling?

    With the following code, when you scroll up and down you get lots of "called" output.
    I will know when my jtable is updated, so is there
    some way I can get the scrollpane to buffer the entire jtable component
    so that subsequent scrolling just does drawing of the appropriate part
    of the jtable from a buffered image? Note that the cells still need to
    be editable (I've got cell editors). Possible? Here's the code :
    public class TableBufTest {
        public static void main(String[] args) {
            String[][] data = new String[30][2];
            for (int i=0; i<2; i++) {
                for (int j=0; j<30; j++) {
                    data[j] = Integer.toString(j*10 + i);
    String[] columnNames = new String[] {"1", "2"};
    final JLabel jLabel = new JLabel();
    JTable table = new JTable(data, columnNames);
    table.getColumnModel().getColumn(0).setCellRenderer(new TableCellRenderer() {
    public Component getTableCellRendererComponent(JTable table, Object value,
    boolean isSelected, boolean hasFocus,
    int row, int column) {
    System.out.println("called");
    jLabel.setText((String) value);
    return jLabel;
    JScrollPane scrollPane = new JScrollPane(table);
    JFrame jFrame = new JFrame();
    jFrame.getContentPane().add(scrollPane);
    jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    jFrame.setSize(200,200);
    jFrame.setLocation(300,300);
    jFrame.show();
    Thanks!

    Thanks.
    I ended up doing a couple of things - first of all using JLabels instead of JTextFields
    and then creating my own FastJLabel using the DefaultTableCellRenderer as a basis.
    (I couldn't use it because I have to return different components for different rows.)

  • JTable within JScrollPane (setting BGColor)

    Hello,
    if the JScrollPane is larger than the contained JTable. How can I set the background-color of the arised gap?
    Neither JTable.setBackground(...) nor JScrollPane.setBackground(...) show any effect, i.e. the background-color doesn't change.
    Is there a proper way to avoid this gap, without scrollbars or knowning the exact size of the JTable?
    Yours truly, Raffael Vogler

    http://search.java.sun.com/search/java/index.jsp?qt=%2Btitle%3Ajscrollpane+%2Btitle%3Abackground&nh=10&qp=&rf=1&since=&country=&language=&charset=&variant=&col=javaforums

  • Drag/drop into JTable inside JScrollPane

    Hello,
    I have a table inside a JScrollPane. I can set the table as the DropTarget by the command:
    new DropTarget(table,fileDropTargetListener);
    but I cannot set the JScrollPane be the DropTarget by the same command.
    the problem is that: I cannot set the table to fit the JScrollPane by the command setsize(scrollPane.getSize() ), setPreferedSize(scrollPane.getPreferedSize()), (don't know for what reason, they don't work to fit the scrollpane), therefore when user drags an item to the JScrollPane but outside the table, the drag gesture doesnot display.
    Please anyone help me how to solve this problem. Thank you,
    fantabk

    Yes, I use custom cell renderer and cell editor for ParentTable, which returns NestedTable.
    DnD turned on for the ParentTable, so when the NestedTable is active (some cells selected in it) it receives DnD events, which are turned off for it, and DnD doesn't work.
    Possible solution is to turn DnD for NestedTable (not for ParentTable), and i'll do this if it is impossible to make it work in current configuration.
    So the question is � is this possible do not pass DnD event to NestedTable ?

Maybe you are looking for