Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

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

Posted on 2004-08-02
13
Medium Priority
?
702 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 7
  • 4
13 Comments
 
LVL 92

Assisted Solution

by:objects
objects earned 1000 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 1000 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
The top UI technologies you need to be aware of

An important part of the job as a front-end developer is to stay up to date and in contact with new tools, trends and workflows. That’s why you cannot miss this upcoming webinar to explore the latest trends in UI technologies!

 
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

On Demand Webinar: Networking for the Cloud Era

Did you know SD-WANs can improve network connectivity? Check out this webinar to learn how an SD-WAN simplified, one-click tool can help you migrate and manage data in the cloud.

Question has a verified solution.

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

Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
Suggested Courses

721 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