• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 600
  • Last Modified:

Scrolling in JTable

I have a JTable placed on a JScrollPane. I have about 400 rows of data displayed in the table.

However, to scroll up and down, I can't seem to be able to use PageUP and PageDown keys.

Please help. If you can include a code sample, that'll be great too !

Thanks.
0
psapra
Asked:
psapra
  • 7
  • 3
  • 3
  • +1
1 Solution
 
shaveriCommented:
try the foll..code

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
import java.awt.event.KeyEvent.*;
public class CustomDisplayer extends JPanel {
  CustomDisplayer() {
    setLayout (new BorderLayout());

    // Create data model
    ADataModel myModel = new ADataModel();

    // Create table with model
    JTable table = new JTable (myModel);
    table.addKeyListener(new KeyAdapter(){
      public void keyPressed(KeyEvent e){
            if(e.getKeyCode()==KeyEvent.VK_PAGE_DOWN)
                  System.out.println("VK_PAGE_DOWN");
            if(e.getKeyCode()==KeyEvent.VK_PAGE_UP)
                  System.out.println("VK_PAGE_UP");
      }
    });      

    // Get column model
    TableColumnModel tcm = table.getColumnModel();

    // Get column from table
    //TableColumn column = tcm.getColumn (myModel.getColumnCount()-1);
    // Create renderer
    //TableCellRenderer renderer = new ColorizedCell();
    // Change the cell renderer for the column within table
    //column.setCellRenderer (renderer);

    // Create scrollpane for table
    JScrollPane scrollPane = new JScrollPane(table);

    // Add to Screen
    add (scrollPane, BorderLayout.CENTER);

  }
  public static void main (String args[]) {
    JFrame f = new JFrame ("Table demo");
    JPanel j = new CustomDisplayer();
    f.addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        System.exit(0);
      }
    });
    f.getContentPane().add (j, BorderLayout.CENTER);
    f.setSize (300, 200);
    f.show();
  }
}

class ADataModel extends AbstractTableModel {

  // Imagine the data coming from JDBC
  // With column names from ResultSetMetaData

  String columns[] = {"Name", "Favorite Color"};
  String rows[][] = {
    {"Alexander", "red"},
    {"Jerry", "blue"},
    {"Jim", "black"},
    {"John", "green"},
    {"Mel", "orange"},
    {"Michael", "lightGray"},
    {"Peter", "magenta"},
    {"Randy", "green"},
    {"Rob", "cyan"},
    {"Scott", "yellow"},
    {"Susan", "darkGray"}
  };

  // Save array lengths for performance reasons
  private int numColumns = columns.length;
  private int numRows = rows.length;

  public int getColumnCount() {
    return numColumns;
  }

  public int getRowCount() {
    return numRows;
  }

  public Object getValueAt (int row, int column) {
    return rows[row][column];
  }

  public String getColumnName (int columnIndex) {
    return columns[columnIndex];
  }
}

0
 
psapraAuthor Commented:
My apologies if I did not explain myself very clearly.

What I would really like to do is to ACTUALLY scroll up and down the list when PgUP and PgDN keys are pressed. The sample code that you provided only prints a message in the debug window.

If you have any idea on how to achieve that, please let me know.

Thanks.
0
 
vladi21Commented:
psapra: which L&F u use?
0
The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

 
vladi21Commented:
* Like all JComponent classes, you can use
 * {@link JComponent#registerKeyboardAction} to associate an
 * {@link Action} object with a {@link KeyStroke} and execute the
 * action under specified conditions.
 * <p>
 * See <a href="http://java.sun.com/docs/books/tutorial/ui/swing/table.html">How to Use Tables</a>
 * in <a href="http://java.sun.com/Series/Tutorial/index.html"><em>The Java Tutorial</em></a>
 * for further documentation.
 * <p>
 * For the keyboard keys used by this component in the standard Look and
 * Feel (L&F) renditions, see the
 * <a href="doc-files/Key-Index.html#JTable">JTable</a> key assignments.
 * <p>
0
 
vladi21Commented:
what is ur swing version,platform and L&F?


try
//Sets the L&F object that renders this component.
table.setUI(javax.swing.plaf.basic.BasicTableUI.createUI());

u can find code for scrolling in
javax\swing\plaf\basic\BasicTableUI.java

look
installKeyboardActions() ->
        registerScrollKey(KeyEvent.VK_PAGE_UP,       0, false,  true, false); ->
        registerKeyboardAction(->

PagingAction()
PagingAction.actionPerformed ->
NavigationalAction.actionPerformed_>
moveWithinTableRange
....


0
 
psapraAuthor Commented:
vladi21,

I am using swing 1.0.1 ( included with Visual Cafe 3.0 IDE ) on NT 4.0.

The default look and feel selected by the IDE is Metal. Does that make a difference though ?

Here's the code generated by the IDE when I put a JTable on a JScrollPane. Everything here is going on a JDialog.

jscrollpane1.setOpaque(true);
getContentPane().add(jscrollpane1);
jscrollpane1.setBounds(12,16,900,318);
jscrollpane1.getViewport().add(jtable1);
jtable1.setBounds(0,0,897,315);

Let me know if you need more information. I am still struggling :-(

Thanks.
0
 
vladi21Commented:
use latest swing version and all be OK
if you cannot try implement same fuctionality as in javax.swing.plaf.basic.BasicTableUI
of latest Swing
0
 
fmaritatoCommented:
Here is how you activate the pg up and pg down buttons for
a JTable:

 table.registerKeyboardAction(new ActionListener() {
            public void actionPerformed(ActionEvent _event) {
                int temp = table.getSelectedRow();
                int max = table.getRowCount();
                if (temp+1<max) {
                    table.removeRowSelectionInterval(temp,temp);
                    table.addRowSelectionInterval(temp+1,temp+1);
                }
            }
        },
            KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_DOWN,0),
            WHEN_IN_FOCUSED_WINDOW);    

table.registerKeyboardAction(new ActionListener() {
            public void actionPerformed(ActionEvent _event) {
                int temp = table.getSelectedRow();
                int max = table.getRowCount();
                if (temp>0) {
                    table.removeRowSelectionInterval(temp,temp);
                    table.addRowSelectionInterval(temp-1,temp-1);
                }
            }
        },
            KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP,0),
            WHEN_IN_FOCUSED_WINDOW);        

Let me know if this works for you...
0
 
vladi21Commented:
fmaritato - can u post comments first???
0
 
fmaritatoCommented:
vladi21,

The rules for this site say to post an answer when you are
100% sure of the solution. I have been using this code
successfully for a long time now in our current product and I am so confident. Of course, psapra may want to scroll more than one line at a time, but my example illustrates how to get the table to respond to key events which is what he asked.

One gotcha I forgot to mention: The focus needs to be in the table for this to work (obviously), but this may take one or two clicks depending on what version of swing you are using.

0
 
vladi21Commented:
fmaritato - in my table all work fine
without additional uggly code :)

fmaritato - what is ur Swing version?


0
 
shaveriCommented:
psapra,
I think you have not checked the code properly,the same code I  modified with populating more items in the JTable.try the code once again...I think there is no need to explicitly add the paga up and page up facility for Jtable,it is in built

/*
// header - edit "Data/yourJavaHeader" to customize
// contents - edit "EventHandlers/Java file/onCreate" to customize
//
*/



                import java.awt.*;
                import java.awt.event.*;
                import javax.swing.*;
                import javax.swing.table.*;
                import java.awt.event.KeyEvent.*;
                public class CustomDisplayer extends JPanel {
                  CustomDisplayer() {
                    setLayout (new BorderLayout());

                    // Create data model
                    ADataModel myModel = new ADataModel();

                    // Create table with model
                    JTable table = new JTable (myModel);
                    table.addKeyListener(new KeyAdapter(){
                public void keyPressed(KeyEvent e){
                if(e.getKeyCode()==KeyEvent.VK_PAGE_DOWN)
                System.out.println("VK_PAGE_DOWN");
                if(e.getKeyCode()==KeyEvent.VK_PAGE_UP)
                System.out.println("VK_PAGE_UP");
                }
                    });

                    // Get column model
                    TableColumnModel tcm = table.getColumnModel();

                    // Get column from table
                    //TableColumn column = tcm.getColumn
                //(myModel.getColumnCount()-1);
                    // Create renderer
                    //TableCellRenderer renderer = new ColorizedCell();
                    // Change the cell renderer for the column within table
                    //column.setCellRenderer (renderer);

                    // Create scrollpane for table
                    JScrollPane scrollPane = new JScrollPane(table);

                    // Add to Screen
                    add (scrollPane, BorderLayout.CENTER);

                  }
                  public static void main (String args[]) {
                    JFrame f = new JFrame ("Table demo");
                    JPanel j = new CustomDisplayer();
                    f.addWindowListener(new WindowAdapter() {
                      public void windowClosing(WindowEvent e) {
                        System.exit(0);
                      }
                    });
                    f.getContentPane().add (j, BorderLayout.CENTER);
                    f.setSize (300, 200);
                    f.show();
                  }
                }

                class ADataModel extends AbstractTableModel {

                  // Imagine the data coming from JDBC
                  // With column names from ResultSetMetaData

                  String columns[] = {"Name", "Favorite Color"};
                  String rows[][] = {
                    {"Alexander", "red"},
                    {"Jerry", "blue"},
                    {"Jim", "black"},
                    {"John", "green"},
                    {"Mel", "orange"},
                    {"Michael", "lightGray"},
                    {"Peter", "magenta"},
                    {"Randy", "green"},
                    {"Rob", "cyan"},
                    {"Scott", "yellow"},
                    {"Susan", "darkGray"},
                                                            {"Alexander", "red"},
                    {"Jerry", "blue"},
                    {"Jim", "black"},
                    {"John", "green"},
                    {"Mel", "orange"},
                    {"Michael", "lightGray"},
                    {"Peter", "magenta"},
                    {"Randy", "green"},
                    {"Rob", "cyan"},
                    {"Scott", "yellow"},
                    {"Susan", "darkGray"},
                                                            {"Alexander", "red"},
                    {"Jerry", "blue"},
                    {"Jim", "black"},
                    {"John", "green"},
                    {"Mel", "orange"},
                    {"Michael", "lightGray"},
                    {"Peter", "magenta"},
                    {"Randy", "green"},
                    {"Rob", "cyan"},
                    {"Scott", "yellow"},
                    {"Susan", "darkGray"}
                  };

                  // Save array lengths for performance reasons
                  private int numColumns = columns.length;
                  private int numRows = rows.length;

                  public int getColumnCount() {
                    return numColumns;
                  }

                  public int getRowCount() {
                    return numRows;
                  }

                  public Object getValueAt (int row, int column) {
                    return rows[row][column];
                  }

                  public String getColumnName (int columnIndex) {
                    return columns[columnIndex];
                  }
                }


               
0
 
psapraAuthor Commented:
fmaritato:

I tried what you suggested - and it does activate the pgup and pgdn keys. However, I was hoping I wouldn't have to specifiy how many rows I would like to scroll. It would have been nice if  the table could automatically figure this out.

Also, when I scroll right now, the scroll bar goes to the next page but that page does not move into the focus. Is that supposed to be this way ?

Why is it so hard to use JTable ?

shaveri:

I tried your suggestion too. May be it's something specific to the swing version etc. but in my case, that just doesn't work at all. Or may be I am doing something I should not - I don't know.

Thanks.
0
 
fmaritatoCommented:
psapra,

> It would have been nice if  the table could automatically
> figure this out.

There should be a tricky way to do this, but it would probably
involve querying the JViewport inside the scrollpane for the
visible rectangle and then doing some math with the cell height
and figure it out that way. Sounds kind of annoying. You
may want to just set the increment to a percentage of the
total number of rows, or a flat value of 15-20 or something.

> Also, when I scroll right now, the scroll bar goes to the next
> page but  that page does not move into the focus. Is that
> supposed to be this way ?

To fix this, you need to do the following:

1. Keep a handle to the JScrollPane that you added the
  table to.
2. Once you set the selected row, get the viewport for
  the scrollpane and scrollrecttovisible. For example,

  sp.getViewport().scrollRectToVisible(table.getCellRect(row, col, false));

> Why is it so hard to use JTable ?

  It would be no fun if it was easy!!! :)

Let me know how this goes...
0
 
vladi21Commented:
download latest Swing version...
0
 
shaveriCommented:
psapra,
         is my code is not working? or what else you are expecting more from us....
0

Featured Post

Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

  • 7
  • 3
  • 3
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now