Solved

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

Posted on 2004-08-02
13
624 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
Comment Utility
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
Comment Utility
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
Comment Utility
Yes thats what I suggested, thanks for saving me the time to type it out :)
0
 
LVL 37

Expert Comment

by:zzynx
Comment Utility
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
Comment Utility
> 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
Comment Utility
> 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
Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

 
LVL 37

Expert Comment

by:zzynx
Comment Utility
>> 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
Comment Utility
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
Comment Utility
Worked exactly as I wanted it.  
Much Appreciation.

Regards,
John
0
 
LVL 92

Expert Comment

by:objects
Comment Utility
Glad we could help :)
0
 
LVL 37

Expert Comment

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

Expert Comment

by:objects
Comment Utility
Thanks John :-)
0

Featured Post

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
sumDigits  challenge 7 60
solarwind tftp server 2 30
eclipse formatting 6 38
Java / Linux and Regular Expressions 11 43
INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
This video teaches viewers about errors in exception handling.

772 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

Need Help in Real-Time?

Connect with top rated Experts

8 Experts available now in Live!

Get 1:1 Help Now