Solved

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

Posted on 2004-08-02
13
631 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
 
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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

For customizing the look of your lightweight component and making it look lucid like it was made of glass. Or: how to make your component more Apple-ish ;) This tip assumes your component to be of rectangular shape and completely opaque. (COD…
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.

914 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

15 Experts available now in Live!

Get 1:1 Help Now