Scroll bar in a JTable

Hello,
can anyone tell me as to how i can set the scrollbar position to the top after i populate a JTable ?

It'll be something like
scrollPane.getVerticalScrollBar().setValue(0);However, depending on how you're populating your table, you may have to invoke this after the current operation has completed 'cos with some components the refresh from the model causes it to scroll to the bottom again. If this happens then try using SwingUtilities.invokeLater.
Hope this helps.

Similar Messages

  • No horizontal scroll bar on the Jtable. In order to see long column.....

    No horizontal scroll bar on the tJable.
    In order to see long cell data we have to eliminate other columns of the table.
    I need an horizontal scroll bar on the JTable if the data in a cell is longer.
    Could somebody help me out?
    Thanks in advance.

    in the jtable use following method :
    myTable.setAutoResizeMode(this.AUTO_RESIZE_OFF);
    KR,
    Jan

  • Horizontal scroll bar is in JTable

    I am doing following code to set horizontal and vertical scroll bar to Table. vertical is working nicely but horizontal is not added to table and all colum of table got shrink and hardly visible. so i want to set horizontal scrollbar as needed.
    how can that possible. looking for response
    mTable.setPreferredScrollableViewportSize(new Dimension(TABLE_WIDTH, TABLE_HEIGHT));
    mTable.setRowHeight(TABLE_ROW, TABLE_ROWHEIGHT);
    mTable.getTableHeader().setResizingAllowed(false);
    mTable.setGridColor(Color.darkGray);
    mTable.getTableHeader().setReorderingAllowed(false);
    mScrollPane = new JScrollPane(mTable);
    mScrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    mScrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
    Message was edited by:
    Prashant_SDN

    that looks odd. what is wrong in this case
    Nothing's wrong. The columns all start up with the same default width.
    If you want it fitted to width on being shown and then become adjustable then you should invoke that change in a listener which executes when the component is shown (the reliable way to do this is use a HierarchyListener which checks isShowing() and then executes if that's true, then deregisters itself).

  • Disabling of Horizantal scroll bar in a JTable

    Hi,
    I have a JTable.I disabled the whole table by using
    JTableObj.setEnabled(false); But here the horizantal scrollbar is
    still enabled means I can drag the scroollbar.
    I used like JScrollpaneObj.gethorizantalscrollbar().setEnabled(false)....but still it is not working..
    How can I make my horizatal scrollbar disable.
    Regards,

    I used like JScrollpaneObj.gethorizantalscrollbar().setEnabled(false)....but still it is not working..Works fine for me.
    If you need further help then you need to create a [url http://homepage1.nifty.com/algafield/sscce.html]Short, Self Contained, Compilable and Executable, Example Program (SSCCE) that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.
    And don't forget to use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags so the code retains its original formatting.

  • JTable can't display column names and scroll bar in JDialog !!

    Dear All ,
    My flow of program is JFrame call JDialog.
    dialogCopy = new dialogCopyBay(frame, "Bay Name Define", true, Integer.parseInt(txtSourceBay.getText()) ,proVsl ,300 ,300);
    dialogCopy.setBounds(0, 0, 300, 300);
    dialogCopy.setVisible(true);        Then,I set the datasource of JTable is from a TableModel.
    It's wild that JTable can diplay the data without column names and scroll bar.
    I have no idea what's going wrong.Cause I follow the Sun Tutorial to code.
    Here with the code of my JDialog.
    Thanks & Best Regards
    package com.whl.panel;
    import com.whl.vslEditor.vslDefine;
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.Frame;
    import javax.swing.JDialog;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.AbstractTableModel;
    public class dialogCopyBay extends JDialog {
        vslDefine glbVslDefine;
        int lvCnt = -1;
        JTable tableCopyBay;
        int bgnX = 0;
        int bgnY = 30;
        int tableWidth = 100;
        int tableHeight = 100;
        public dialogCopyBay(Frame frame, String title, boolean modal, int sourceBay,
                vslDefine pVslDefine, int ttlWidth, int ttlHeight) {
            super(frame, title, true);
            Container contentPane = getContentPane();
            System.out.println("dialogCopyBay Constructor");
            glbVslDefine = null;
            glbVslDefine = pVslDefine;
            copyBayModel copyBay = new copyBayModel((glbVslDefine.getVslBayStructure().length - 1),sourceBay);
            tableCopyBay = new JTable(copyBay);
            tableCopyBay.setPreferredScrollableViewportSize(new Dimension(tableWidth, tableHeight));
            JScrollPane scrollPane = new JScrollPane(tableCopyBay);
            scrollPane.setViewportView(tableCopyBay) ;
            tableCopyBay.setFillsViewportHeight(true);
            tableCopyBay.setBounds(bgnX, bgnY, tableWidth, tableHeight);
            tableCopyBay.setBounds(10, 10, 100, 200) ;
            contentPane.setLayout(null);
            contentPane.add(scrollPane);
            contentPane.add(tableCopyBay);
        class copyBayModel extends AbstractTableModel {
            String[] columnNames;
            Object[][] dataTarget;
            public copyBayModel(int rowNum ,int pSourceBay) {
                columnNames = new String[]{"Choose", "Bay Name"};
                dataTarget = new Object[rowNum][2];
                for (int i = 0; i <= glbVslDefine.getVslBayStructure().length - 1; i++) {
                    if (pSourceBay != glbVslDefine.getVslBayStructure().getBayName() &&
    glbVslDefine.getVslBayStructure()[i].getIsSuperStructure() == 'N') {
    lvCnt = lvCnt + 1;
    dataTarget[lvCnt][0] = false;
    dataTarget[lvCnt][1] = glbVslDefine.getVslBayStructure()[i].getBayName();
    System.out.println("lvCnt=" + lvCnt + ",BayName=" + glbVslDefine.getVslBayStructure()[i].getBayName());
    public int getRowCount() {
    return dataTarget.length;
    public int getColumnCount() {
    return columnNames.length;
    public String getColumnName(int col) {
    return columnNames[col];
    public Object getValueAt(int rowIndex, int columnIndex) {
    return dataTarget[rowIndex][columnIndex];
    public Class getColumnClass(int c) {
    return getValueAt(0, c).getClass();
    public boolean isCellEditable(int row, int col) {
    if (col == 1) {
    // Bay Name Not Allow To modify
    return false;
    } else {
    return true;
    public void setValueAt(Object value, int row, int col) {
    dataTarget[row][col] = value;
    fireTableCellUpdated(row, col);

    Dear DB ,
    I am not sure what you mean.
    Currently,I don't undestand which code is error.
    And I also saw some example is add JTable and JScrollPane in JDialog.
    Like Below examle in Sun tutorial
    public class ListDialog extends JDialog implements MouseListener, MouseMotionListener{
        private static ListDialog dialog;
        private static String value = "";
        private JList list;
        public static void initialize(Component comp,
                String[] possibleValues,
                String title,
                String labelText) {
            Frame frame = JOptionPane.getFrameForComponent(comp);
            dialog = new ListDialog(frame, possibleValues,
                    title, labelText);
         * Show the initialized dialog. The first argument should
         * be null if you want the dialog to come up in the center
         * of the screen. Otherwise, the argument should be the
         * component on top of which the dialog should appear.
        public static String showDialog(Component comp, String initialValue) {
            if (dialog != null) {
                dialog.setValue(initialValue);
                dialog.setLocationRelativeTo(comp);
                dialog.setVisible(true);
            } else {
                System.err.println("ListDialog requires you to call initialize " + "before calling showDialog.");
            return value;
        private void setValue(String newValue) {
            value = newValue;
            list.setSelectedValue(value, true);
        private ListDialog(Frame frame, Object[] data, String title,
                String labelText) {
            super(frame, title, true);
    //buttons
            JButton cancelButton = new JButton("Cancel");
            final JButton setButton = new JButton("Set");
            cancelButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    ListDialog.dialog.setVisible(false);
            setButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    ListDialog.value = (String) (list.getSelectedValue());
                    ListDialog.dialog.setVisible(false);
            getRootPane().setDefaultButton(setButton);
    //main part of the dialog
            list = new JList(data);
            list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
            list.addMouseListener(new MouseAdapter() {
                public void mouseClicked(MouseEvent e) {
                    if (e.getClickCount() == 2) {
                        setButton.doClick();
            JScrollPane listScroller = new JScrollPane(list);
            listScroller.setPreferredSize(new Dimension(250, 80));
    //XXX: Must do the following, too, or else the scroller thinks
    //XXX: it's taller than it is:
            listScroller.setMinimumSize(new Dimension(250, 80));
            listScroller.setAlignmentX(LEFT_ALIGNMENT);
    //Create a container so that we can add a title around
    //the scroll pane. Can't add a title directly to the
    //scroll pane because its background would be white.
    //Lay out the label and scroll pane from top to button.
            JPanel listPane = new JPanel();
            listPane.setLayout(new BoxLayout(listPane, BoxLayout.Y_AXIS));
            JLabel label = new JLabel(labelText);
            label.setLabelFor(list);
            listPane.add(label);
            listPane.add(Box.createRigidArea(new Dimension(0, 5)));
            listPane.add(listScroller);
            listPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
    //Lay out the buttons from left to right.
            JPanel buttonPane = new JPanel();
            buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.X_AXIS));
            buttonPane.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10));
            buttonPane.add(Box.createHorizontalGlue());
            buttonPane.add(cancelButton);
            buttonPane.add(Box.createRigidArea(new Dimension(10, 0)));
            buttonPane.add(setButton);
    //Put everything together, using the content pane's BorderLayout.
            Container contentPane = getContentPane();
            contentPane.add(listPane, BorderLayout.CENTER);
            contentPane.add(buttonPane, BorderLayout.SOUTH);
            pack();
        public void mouseClicked(MouseEvent e) {
            System.out.println("Mouse Click");
        public void mousePressed(MouseEvent e) {
            throw new UnsupportedOperationException("Not supported yet.");
        public void mouseReleased(MouseEvent e) {
            throw new UnsupportedOperationException("Not supported yet.");
        public void mouseEntered(MouseEvent e) {
            throw new UnsupportedOperationException("Not supported yet.");
        public void mouseExited(MouseEvent e) {
            throw new UnsupportedOperationException("Not supported yet.");
        public void mouseDragged(MouseEvent e) {
            throw new UnsupportedOperationException("Not supported yet.");
        public void mouseMoved(MouseEvent e) {
            throw new UnsupportedOperationException("Not supported yet.");
         * This is here so that you can view ListDialog even if you
         * haven't written the code to include it in a program.
    }

  • JTable column movement and scroll bar

    Hello:
    I have a JTable with about 30-40 columns. Sometimes I would like to drag the column from rightmost to closer to the left end. I am not able to do that in one shot. and instead have to do it in multiple steps. Is there a way for the scroll bar to sort of move alongside the column as I drag it along?

    i dont know if there is way off hand. But you can put your own mouseListener of the JScrollPane and i am sure there is some method to check if you are dragging the JTable and if you are move the JScrollBar in the direction.
    I think that you are going to have to make you own implementation of this.
    David

  • Horizontal scroll Bars not coming in JTable

    Hi,
    If a user streches any column of the jtable to the right such that its values are not visible properly. Then should the horizontal scroll bar come in the scrollpane in which table is there.??
    If Yes then how can I do it?
    I have seen when no of rows becomes more than the display area of the table then vertical scrollbar are coming automatically. but not Horizontal scroll bars.
    Please help

    sorry for my previous mistype, here is the right solutions to your problem.
    As default the JTable will auto resize your column width, if you want horizon scrollbar
    you must do following below steps:
    JTable tableview = new JTable (model) ;
    tableview.setAutoResizeMode (JTable.AUTO_RESIZE_OFF) ;
    JScrollPane scrollpane = new JScrollPane (tableview,
    ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
    ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED) ;
    JPanel p ;
    p.add (scrollpane) ;
    This can works for you !

  • JTabel Horizontal scroll bar problem

    Hi,
    I want a horizontal scroll bar added to my table
    hence I do this
    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    but the problem is If I increase the size of frame
    the cells do not resize hence there is a gap after
    the last column.
    How do I remove this gap

    Please reduce the container size in the screen thru SE51 that automatically create the scroll
    or check whether in the attributes of the screen "Hold scroll positio" not to be checked

  • Horizontal Scroll Bar does not show

    I have a method which creates a table with values and displays it in a dialog. However, the horizontal scroll bars do not appear, even though there is are columns that are not seen in the view. Here is my code:
         private void setTable()
              Object columns[] = headerLST.toArray(),
                        rows[][] = new Object[rowLST.size()][headerLST.size()];     
              for(int x = 0; x < rowLST.size(); x++)
                   java.util.List list1 = (java.util.List)rowLST.get(x);
                   for(int y = 0; y < list1.size(); y++)
                        rows[x][y] = (String)list1.get(y);     
              DefaultTableModel tValues = new DefaultTableModel(rows, columns);
    JTable tableA = new JTable(tValues);
         tableA.setRowHeight(27);
                   tableA.setRowSelectionAllowed(false);
                   tableA.setColumnSelectionAllowed(false);
                   tableA.setFont(new Font("Dialog", Font.BOLD, 12));
              int minColWidth = 120, maxColWidth = 200;
              for(int y = 0; y < tableA.getColumnCount(); y++)
                   TableColumn tbc = tableA.getColumnModel().getColumn(y);
                   tbc.setPreferredWidth(minColWidth);     
                   tbc.setMinWidth(minColWidth);
                   tbc.setMaxWidth(maxColWidth);
              scrollA = new JScrollPane(tableA);
              this.getContentPane().add(scrollA, BorderLayout.CENTER);
    Can someone tell me what I am missing?
    Thanks
    Augustine

    You need this
    tableA.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    otherwise it will always try and fit the table to the space available

  • Horizontal scroll bar at top in JScrollPane

    Hi,
    How can i get the horizontal scroll bar to be on the top instead of bottom
    here is my code
    TableModel tableModel = new TableModel(totalData,
    columnHeader);
    JTable table = new JTable(tableModel);
    JScrollPane scrollPane = new JScrollPane(table);
    Ashish

    Hi Ash
    I dont know whether this is feasible please sorry if i am wrong.
    Create a JPanel and add scroll bar to the left and top.
    I have posted a Q in the subject JDialog Esc Key. please answer the Q for me.
    Lakshmi.

  • How to shift Verical scroll bar from right to left??

    hi..
    I have added a JTable to a JScrollPane. This adds a verical scroll bar to the right of my table.
    Now I want to have this vertical scroll bar added to the left of my table.
    is it possible? if yes then suggest how??

    setComponentOrientation( ComponentOrientation.RIGHT_TO_LEFT)

  • Scroll Bar code in Awt Required Plz Help me

    Hi,
    My requirment is to add Vertical Scrollbar to the table.There are 12 rows in a table like from January to December.
    I am able to see data of rows as jan,feb,mar,apr only .
    i want to see the data of rows of next months by adding vertical scroll bar using Awt code.
    I added vertical scroll bar using awt code. When i click on that Vertical scroll bar event is going to below method.
    public void adjustmentValueChanged(AdjustmentEvent e) {
    I tried with some logic inside above method but it is not working.what is the code i have to write inside the above method inorder to scroll the next months.
    Plz Help me.
    Thanks In Advance.........

    But i want to do this code In Using Awt only......Well, a JTable is a Swing component so I have no idea what you are talking about.
    To control the size of the table you can use:
    table.setPreferredScrollableViewportSize(???);
    JScrollPane scrollPane = new JScrollPane( table );

  • Keep vertical scroll bar still y JScrollPane

    Hello all!
    I have got a JTable added into a JScrollPane, which scroll bars are always shown.
    I have to repaint the JTable each 3 seconds and I would like to keep the vertical scroll bar in its original position, for example if I am watching row 24 of the JTable when the JTable is repainted I would like the vertical scroll bar to be in the same position as it was before repainting because now the vertical scroll bar is repainted always at the top...
    With the horizontal bar it works, the bar does not move from its previous state when the JTable is repainted...
    Any idea of what is happening?
    Thanks in advance :)

    This would do for u! ... do it after you have updated the table with the new rows... if you are not using the default table model then you can still get the row count through your JTable object ...
    This part moves the scrollbar to the last row coz im doing "myDefaultTableModel.getRowCount()-1", you can keep the current row index in an instance level variable bjust before refreshing the table and use it in this.setRowSelectionInterval() method ...
    this.setRowSelectionInterval(myDefaultTableModel.getRowCount()-1, myDefaultTableModel.getRowCount()-1);
    this.setColumnSelectionInterval(1, 1); //didnt need any specific column coz I wanted the row basically..
    this.scrollRectToVisible(this.getCellRect(this.getSelectedRow(), 1, true));This basically selects the given row and then moved the scrollbar over to that point as well ...
    OR, here's another alternative!! you can also get the current scrollbar value similarly jsut before refreshing and pass that on to this method ...
    this.jScrollPane1.getVerticalScrollBar().setValue(jScrollPane1.getVerticalScrollBar().getValue());Hope it helps...
    Cheers!
    Asim

  • Change color of the scroll bar?

    I am trying to turn my entire application black with white or some light colored text.
    Is there some way I can change the color of the scroll bar?
    Also, if I have a JTable, there is a bright grey border I would like to dim down a bit.
    Any guidance would is appreciated.

    Hi,
    This code will show you the current UI settings.
    If you want to change ie. the scrollbar background use:
    UIManager.put("Scrollbar.background", your Color);
    Hope this helps.
    Regards,
    Matt
    Java Developer Technical Support
    Sun Microsystems
    import javax.swing.UIManager;
    import javax.swing.UIDefaults;
    import java.util.*;
    class UIList {
        public static void main(String args[]) {
            // Groups of item objects
            Vector itemGroups = new Vector();
            Hashtable itemList = new Hashtable();
            UIDefaults uiDefaults = UIManager.getDefaults();
            for (Enumeration enum = uiDefaults.keys(); enum.hasMoreElements(); ) {
                Object setting = enum.nextElement();
                String settingName = setting.toString();
                int dotIndex = settingName.indexOf(".");
                if (dotIndex != -1)
                    settingName = settingName.substring(0, settingName.indexOf("."))
                if (itemList.containsKey(settingName)) {
                    Integer groupNum = (Integer)itemList.get(settingName);
                    Vector group = (Vector)itemGroups.elementAt(groupNum.intValue())
                    group.add(setting);
                else {
                    itemList.put(settingName, new Integer(itemGroups.size()));
                    Vector group = new Vector();
                    group.add(setting);
                    itemGroups.add(group);
            for (int counter = 0; counter<itemGroups.size(); counter++) {
                Vector items = (Vector)itemGroups.elementAt(counter);
                System.out.println("");
                for (int counter2 = 0; counter2<items.size(); counter2++) {
                    Object setting = items.elementAt(counter2);
                    System.out.println(setting + " = " + uiDefaults.get(setting));
            System.out.println("\nDone.");
            System.exit(0);
    }

  • MENU's are coming with the scroll bar

    Hi,
    I have a problem like this, I am migrating one menu file from a forms6i to 10G after that i tried to put that menu in the form then i found that the menus are coming with the scroll bar is there any parameter so that i can set that to false so i can see all the menus at one time.
    Thanks in advance.
    Saravanan.K

    below is my code.
    Display will have some graphics, the mouse click on the part of the graphics will produce different values in the table. class DatabaseDataDisplay has the JTable who display the values.
    Display.addMouseListener(new MouseAdapter()
    {  public void mousePressed(MouseEvent evt)
    //get the location of the mouse
              int x = evt.getX();
              int y = evt.getY();
              current = find(x, y);
    if(current!=-1)
    DatabaseDataDisplay D_Display=new DatabaseDataDisplay(Table_Name, current);
                                       //remove the old panel
                        WholePanel.remove(scrollPane5);
              //add the new DataPanel
    JScrollPane scrollPane5 = new JScrollPane(D_Display,
    JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
    JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    WholePanel.add(scrollPane5, new GridBagConstraints(0, 1, 1, 1, 1.0, 1.0,GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 2, 0, 2), 659, 5));
    /*if I put a repaint() here, the value on the table will always the values of the first time values when I click the mouse*/
    WholePanel.validate();

Maybe you are looking for

  • Safari and iTunes store crashing after 10.8.4 update

    Hi, Since I have updated to the 10.8.4 OS on my 27inch Late 2012 iMac (3.4 GHz Intel Core i7) I am having trouble with applications which crash instantly upon opening them. I have tried opening these applications about 30-40 times and sent the report

  • How to get list of block identifiers in a empty table and an empty index

    We have an application that has issue with ITL waits: this application is running many INSERT statements on a table that has 2 NUMBER columns and one primary key index. The application is designed to run INSERT statements but they are never committed

  • Skype hoax on Panasonic Viera TVs

    Here is the deal!  I purchased a 55" Panasonic Vierra TV which boasted supporting Skype.  Upon setup, the Skype App would not work until I had the video camera.  Purchased the Panasonic Video Camera to get everything working only to find out that the

  • 180 days depreciation as per IT act

    Hi, I want to post 180 days depreciation ( Ours FSV is AP to Mar, if i acquire asset from Apr to Sep it should calculate full year depreciation and if i purchase after, it should calculate depreciation for 180 days as per IT Act, for that i've made s

  • Help with Performance of Jquery in IE8

    Hi, I'm new to Jquery and not sure if this is cause by Jquery or CSS? I have this demo that runs good everywhere except ie8. Any help appreciated. http://www.lab2x.com/testdrive/hc/20-mapa/demo3/ Today I've learned that using css display is better th