Solved

Scrolls to Always Show Selected Row in JTable on Top of scrollpane

Posted on 2004-08-02
13
650 Views
Last Modified: 2012-05-05
Experts,
  I am writing a simple lookup window.  It has a table with two columns(column 1 is abbreviations, and column 2 is the description).  The window provides this incremental search kind of capability(as you type in the search JTextField, it highlights and scroll to the closest match on the table).  The problem I have is this:  I managed to get it to highlight and scroll to show the match item on the table BUT what I would like to be able to do is to ALWAYS have the highlighted/matched item to be on top of the table.  
Example: Table has 5 rows (a,b,c,d,e) but only two rows are visible(a &b)
              When I typed in d, it scrolls down two rows and shows c and d
              What I really want is for it to scroll far enough to ensure that d would be the topmost visible row on the table(show d and e instead of c and d).
              I want this same effect regardless it's scrolling up or down.

Here's the code snippet that does the highlighting and scrolling (but highlighted item does not go to top of table)
       
     if(str.startsWith(searchPattern))
        {
          lookupTable.setRowSelectionInterval(i,i);
          Rectangle rect = lookupTable.getCellRect(i,0,true);
          lookupTable.scrollRectToVisible(rect);
          break;
        }

Any help is greatly appreciated,

John

   
0
Comment
Question by:johnchan2000
  • 7
  • 4
13 Comments
 
LVL 92

Assisted Solution

by:objects
objects earned 250 total points
ID: 11699358
you need access to the scroll pane, which will allow you to set the viewport position exactly where you require it.
0
 
LVL 37

Accepted Solution

by:
zzynx earned 250 total points
ID: 11701410
I guess this demonstrates what you want:

Fill in the row to jump to and press the <Go> button.
The magic is in the jButton1ActionPerformed() function.

/*
 * TableScrollDemo.java
 *
 */

import javax.swing.*;
import java.awt.*;
/**
 *
 * @author  zzynx
 */
public class TableScrollDemo extends javax.swing.JFrame {

    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane theScrollPane;
    private javax.swing.JTable theTable;
    private javax.swing.JTextField theTextField;
   
    public TableScrollDemo() {
        initComponents();
        theTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {"0", "Row 1" },
                {"1", "Row 2" },
                {"2", "Row 3" },
                {"3", "Row 4" },
                {"4", "Row 5" },
                {"5", "Row 6" },
                {"6", "Row 7" },
                {"7", "Row 8" },
                {"8", "Row 9" },
                {"9", "Row 10" },
                {"10", "Row 11" },
                {"11", "Row 12" },
                {"12", "Row 13" },
                {"13", "Row 14" },
                {"14", "Row 15" },
                {"15", "Row 16" },
                {"16", "Row 17" },
                {"17", "Row 18" },
                {"18", "Row 19" },
                {"19", "Row 20" },
            },
            new String [] {
                "Column 1", "Column 2"
            }
        ));
        setLocationRelativeTo(null); // center on the screen
    }
   
    private void initComponents() {
        theScrollPane = new javax.swing.JScrollPane();
        theTable = new javax.swing.JTable();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        theTextField = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();

        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                exitForm(evt);
            }
        });

        theScrollPane.setPreferredSize(new java.awt.Dimension(452, 50));
        theTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        theScrollPane.setViewportView(theTable);

        getContentPane().add(theScrollPane, java.awt.BorderLayout.NORTH);

        jLabel1.setText("Scroll to row:");
        jPanel1.add(jLabel1);

        theTextField.setPreferredSize(new java.awt.Dimension(50, 20));
        jPanel1.add(theTextField);

        jButton1.setText("Go!");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jPanel1.add(jButton1);

        getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER);

        pack();
    }

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        try {
            int row = Integer.parseInt(theTextField.getText());
            if (row >= theTable.getRowCount()) return;
            theTable.setRowSelectionInterval(row, row);
            JViewport vp = theScrollPane.getViewport();
            Rectangle rect = theTable.getCellRect(row,0, true);
            vp.setViewPosition( new Point(rect.x, rect.y ) );
            theTable.revalidate();
            theTable.repaint();
        } catch (NumberFormatException e) { }
    }
   
    private void exitForm(java.awt.event.WindowEvent evt) {
        System.exit(0);
    }
   
    public static void main(String args[]) {
        new TableScrollDemo().show();
    }
}

Success.
0
 
LVL 92

Expert Comment

by:objects
ID: 11701491
Yes thats what I suggested, thanks for saving me the time to type it out :)
0
Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

 
LVL 37

Expert Comment

by:zzynx
ID: 11702551
We're here to help as good as possible. Not to provide answers like riddles.
That's why I posted some relevant code that really shows how.
The author of this question will decide.
0
 
LVL 92

Expert Comment

by:objects
ID: 11702586
> The author of this question will decide.

I explained how to do, and you wrote an example implementing my suggestion.
whats there to decide  ???
0
 
LVL 92

Expert Comment

by:objects
ID: 11702612
> Not to provide answers like riddles.

And theres no riddle (even you understood). John knows that all he needs to do is ask if he requires more details on the implementation and I am more than happy to provide clarification.
0
 
LVL 37

Expert Comment

by:zzynx
ID: 11702884
>> Not to provide answers like riddles.
...and certainly not to fill up a thread with quarreling like you do now

>> I am more than happy to provide clarification
Then why aren't you if others do?
Or should I've asked you first if I was allowed to?
0
 
LVL 92

Expert Comment

by:objects
ID: 11702997
I'm not quarrelling :-D  All I did was thank you, sorry if you took that as argumentative (though i'm not sure how).
0
 
LVL 1

Author Comment

by:johnchan2000
ID: 11709611
Worked exactly as I wanted it.  
Much Appreciation.

Regards,
John
0
 
LVL 92

Expert Comment

by:objects
ID: 11710435
Glad we could help :)
0
 
LVL 37

Expert Comment

by:zzynx
ID: 11712647
>> Worked exactly as I wanted it.
Nice!
Thanks for accepting.
0
 
LVL 92

Expert Comment

by:objects
ID: 11722322
Thanks John :-)
0

Featured Post

Free Tool: Postgres Monitoring System

A PHP and Perl based system to collect and display usage statistics from PostgreSQL databases.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
numbers ascending pyramid 101 213
Windows 10 IE Certificate Issue 10 51
pagenation logic how it is working in my code 1 54
going to wrong jsp page 2 33
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.

839 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question