JTable use in JScrollPane

I have a JTable in JScrollPane which has about 116000 rows of data. I would like to get a status count of what rows are displayed at a time when I move down the scollPane. This is to keep a running track of rows displayed in status message when moving down the scrollpane.
SAY : Displaying rows 10 to 40 of 116000 rows. Is there anyway to get this count.

I would use a combination of:
[JScrollPane.getViewport().getViewRect()|http://java.sun.com/javase/6/docs/api/javax/swing/JViewport.html#getViewRect%28%29]
and
[JTable.rowAtPoint()|http://java.sun.com/javase/6/docs/api/javax/swing/JTable.html#rowAtPoint%28java.awt.Point%29]

Similar Messages

  • Deleting a row from a JTable using AbstractTableModel

    Hi,
    Can someone please help me on how should i go about deleting a row in a jtable using the AbstractTableModel. Here i know how to delete it by using vector as one of the elements in the table. But i want to know how to delete it using an Object[][] as the row field.
    Thanks for the help

    Hi,
    I'm in desperate position for this please help

  • Remove Column Headers from a JTable in a JScrollPane

    Hi,
    I'm just wondering how to remove the column headers from a JTable in a JScrollPane.

    Here are two ways to do it, with different visual outcomes...
    import javax.swing.*;
    public class Test {
        public static void main(String[] args) {
            Object[][] rowData = {{"A", "B"}, {"C", "D"}};
            Object[] columnNames = {"col 1", "col 2"};
            JTable table1 = new JTable(rowData, columnNames);
            table1.getTableHeader().setVisible(false);
            JScrollPane sp1 = new JScrollPane(table1);
            JTable table2 = new JTable(rowData, columnNames);
            final JScrollPane sp2 = new JScrollPane(table2);
            JPanel contentPane = new JPanel();
            contentPane.add(sp1);
            contentPane.add(sp2);
            final JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setContentPane(contentPane);
            f.pack();
            SwingUtilities.invokeLater(new Runnable(){
                public void run() {
                    sp2.setColumnHeader(null);
                    f.setLocationRelativeTo(null);
                    f.setVisible(true);
    }

  • Use of JScrollPane

    I try to use the JScrollPane class with a JPanel, which at the time contains a class compounded of several textboxes and other JComponent subclasses.
    I am not using any layout manager (setting every layout manager to null), and though displaying the components properly inside the JFrame, I don't get the JScrollPane (or the JViewPort in it) to recognize the underlying size of the JPanel, therefore not displaying any scrollbars, horizontal or vertical, when setting the JScrollPane horizontal and vertical scrollbar policies to "as needed". First guess, is that I should set some of the JScrollPane properties manually, such as extent, min, max and so on. Perhaps the problem lies on the LayoutManager.
    The strange point, is that whenever you provide as JViewPort component any root class (such as a texarea), everything works as desired.
    Can anybody help? Hope the explanation is clear.
    Thanks in advance.
    Carlos.

    Carlo,
    try setting the preferred size of the JScrollPane. If that doesn't work, You'll probably have to put your JScrollPane on another JPanel and set the size of THAT JPanel (the one that holds the scrollpane).
    If you just add the JScrollPane onto the JFrame, it will normally take up the whole size of the JFrame.
    If you paste up your code, it may help us understand the problem better.

  • Resizing columns in a JTable in a JScrollpane

    I have a JTable in a JScrollpane and I after I load the table, I resize the columns to fit the data (works well).
    The problem is that I want the scrollpane to stay the same size and let the table scroll horizontally inside the viewport. The actual result is the scrollpane stretches to the width of the table causing the user to scroll the panel rather than the scrollpane.
    I've tried setting the scrollbar policy but that didn't work.

    I am passing the JTable to the constructor of the JScrollPane.
    I have a JTable in a JScrollPane that sits on a JPanel which is in a JScrollPane itself.
    After I load the data into the JTable, I resize all of the columns to fit the data.
    The problem is that the JTable resizes wider than original size causing the whole panel to scroll horizontally. I would rather have the JScrollPane that the JTable is in scroll.

  • Sorting Columns in JTable Using Different Comparators

    Is there any way to sort each column in a JTable using different comparators?

    you'll have to write your own tableSorter

  • Updating a JTable using a JTable

    I am looking to update an empty JTable using the data from a JTable containing a set of data.
    I am aware that addRow can be used with the DefaultTableModel from previous discussions on this forum, but I have found this call isn't available when using AbstractTableModel.
    The reason I have been having some problems with this as it is necessary for the AbstractTableModel to be used in the context of the GUI, and I am asking if there is a way to solve this using the AbstractTableModel?
    I am using an AbstractTableModel for both the data table and the table showing all currently and previously selected rows.

    I am using an AbstractTableModel for both the data table and the table showing all currently and previously selected rows.No you aren't. You can't create an Abstract class because not all the methods are implements. You are using a class that extends AbstractTableModel.
    So why not use the DefaultTableModel and make your life simple?

  • Stopping cell editing in a JTable using a JComboBox editor w/ AutoComplete

    Hi there! Me again with more questions!
    I'm trying to figure out the finer parts of JTable navigation and editing controls. It's getting a bit confusing. The main problem I'm trying to solve is how to make a JTable using a combo box editor stop editing by hitting the 'enter' key in the same fashion as a JTextField editor. This is no regular DefaultCellEditor though -- it's one that uses the SwingX AutoCompleteDecorator. I have an SSCCE that demonstrates the issue:
    import java.awt.Component;
    import java.awt.EventQueue;
    import javax.swing.AbstractCellEditor;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.JTable;
    import javax.swing.WindowConstants;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableCellEditor;
    import javax.swing.table.TableModel;
    import org.jdesktop.swingx.autocomplete.AutoCompleteDecorator;
    public class AutoCompleteCellEditorTest extends JFrame {
      public AutoCompleteCellEditorTest() {
        JTable table = new JTable();
        Object[] items = {"A", "B", "C", "D"};
        TableModel tableModel = new DefaultTableModel(2, 2);
        table.setModel(tableModel);
        table.getColumnModel().getColumn(0).setCellEditor(new ComboCellEditor(items));
        getContentPane().add(table);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        pack();
      private class ComboCellEditor extends AbstractCellEditor implements TableCellEditor {
        private JComboBox comboBox;
        public ComboCellEditor(Object[] items) {
          this.comboBox = new JComboBox(items);
          AutoCompleteDecorator.decorate(this.comboBox);
        public Object getCellEditorValue() {
          return this.comboBox.getSelectedItem();
        public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
          comboBox.setSelectedItem(value);
          return comboBox;
      public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
          public void run() {
            new AutoCompleteCellEditorTest().setVisible(true);
    }Problem 1: Starting to 'type' into the AutoCompleteDecorate combo box doesn't cause it to start editing. You have to hit F2, it would appear. I've also noticed this behaviour with other JComboBox editors. Ideally that would be fixed too. Not sure how to do this one.
    Problem 2: After editing has started (say, with the F2 key), you may start typing. If you type one of A, B, C, or D, the item appears. That's all good. Then you try to 'complete' the edit by hitting the 'enter' key... and nothing happens. The 'tab' key works, but it puts you to the next cell. I would like to make the 'enter' key stop editing, and stay in the current cell.
    I found some stuff online suggesting you take the input map of the table and set the Enter key so that it does the same thing as tab. Even though that's not exactly what I desired (I wanted the same cell to be active), it didn't work anyway.
    I also tried setting a property on the JComboBox that says that it's a table cell editor combo box (just like the DefaultCellEditor), but that didn't work either. I think the reason that fails is because the AutoCompleteDecorator sets isEditable to true, and that seems to stop the enter key from doing anything.
    After tracing endless paths through processKeyBindings calls, I'm not sure I'm any closer to a solution. I feel like this should be a fairly straightforward thing but I'm having a fair amount of difficulty with it.
    Thanks for any direction you can provide!

    Hi Jeanette,
    Thanks for your advice. I looked again at the DefaultCellEditor. You are correct that I am not firing messages for fireEditingStopped() and fireEditingCancelled(). Initially I had copied the behaviour from DefaultCellEditor but had trimmed it out. I assumed that since I was extending AbstractCellEditor and it has them implemented correctly that I was OK. But I guess that's not the case! The problem I'm having with implementing the Enter key stopping the editing is that:
    1) The DefaultCellEditor stops cell editing on any actionPerformed. Based on my tests, actionPerformed gets called whenever a single key gets pressed. I don't want to end the editing on the AutoCompleteDecorated box immediately -- I'd like to wait until the user is happy with his or her selection and has hit 'Enter' before ending cell editing. Thus, ending cell editing within the actionPerformed listener on the JComboBox (or JXComboBox, as I've made it now) will not work. As soon as you type a single key, if it is valid, the editing ends immediately.
    2) I tried to add a key listener to the combo box to pick up on the 'Enter' key and end the editing there. However, it appears that the combo box does not receive the key strokes. I guess they're going to the AutoCompleteDecorator and being consumed there so the combo box does not receive them. If I could pick up on the 'Enter' key there, then that would work too.
    I did more reading about input maps and action maps last night. Although informative, I'm not sure how far it got me with this problem because if the text field in the AutoCompleteDecorator takes the keystroke, I'm not sure how I'm going to find out about it in the combo box.
    By the way, when you said 'They are fixed... in a recent version of SwingX', does that mean 1.6.2? That's what I'm using.
    Thanks!
    P.S. - Maybe I should create a new question for this? I wanted to mark your answer as helpful but I already closed the thread by marking the answer to the first part as correct. Sorry!
    Edited by: aardvarkk on Jan 27, 2011 7:41 AM - Added SwingX versioning question.

  • Unable to grow and shrink a JTable within a JScrollPane

    I need help with the following: I want to display a JTable component with a calendar like design. Dragging the size of the parent component (having a border to drag) should dynamically adapt the JTable' size and its cells. Since the JTable has a minimum size shrinking the parent component should show scrollbars if the minimum size is reached horizontal or vertical respectively.
    I have the JTable put ijnto the viewport of a scrollpane and the scrollpane is the child component of a JPanel. So dragging appears with the panel.
    The JTable cells do nicely but from a specific size on there is a grey area on the lower part of the JPanel which is not repainted. What is causing this? What do I have to do? I'm lost in the jungle of invalidate(), repaint(), update(), doLayout() etc.
    Here is my SSCCE (at least I hope it is one):
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.event.ComponentAdapter;
    import java.awt.event.ComponentEvent;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.ListSelectionModel;
    import javax.swing.UIManager;
    import javax.swing.table.AbstractTableModel;
    import javax.swing.table.TableColumn;
    import javax.swing.table.TableModel;
    //public class MyComponent extends JScrollPane
    public class MyComponent extends JPanel
    ///   class data
         static public final long serialVersionUID = -1L;
         static public final int c_ColWidth = 29;
         static public final int c_RowHeight = 18;
         static public final int c_TableWidth = 930;
         static public final int c_TableHeight = 234;
    ///   instance data
         private String[] m_strColHeader = {
              "01", "02", "03", "04", "05", "06", "07", "08", "09", "10",
              "11", "12", "13", "14", "15", "16", "17", "18", "19", "20",
              "21", "22", "23", "24", "25", "26", "27", "28", "29", "30",
              "31",
         private Object[][] m_Data = new Object[12][33];// data array
         private TableModel m_DataModel = new AbstractTableModel() {
              static public final long serialVersionUID = -1L;
              public int getColumnCount() { return m_strColHeader.length; }
              public int getRowCount() { return m_Data != null ? m_Data.length : 0; }
              public Object getValueAt(int row, int col) { return m_Data[row][col]; }
              public String getColumnName(int col) { return m_strColHeader[col]; }
              public Class getColumnClass(int col) { return String.class; }
              public boolean isCellEditable(int row, int col) { return false; }
              public void setValueAt(Object aValue, int row, int col) {
                   m_Data[row][col] = aValue;
         protected BorderLayout myLayout = new BorderLayout();
         protected JTable tableView = new JTable(m_DataModel);
         protected JScrollPane scrollPane = new JScrollPane(tableView);
    ///   public class methods
         static public void main(String[] args)
              try
                   UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
              catch(Exception e)
                   e.printStackTrace();
              MyComponent comp1 = new MyComponent();
              JFrame frame = new JFrame("MyComponent");
              frame.addWindowListener(new WindowAdapter() {
                   public void windowClosing(WindowEvent e) {
                        System.exit(0);
              frame.getContentPane().add(comp1);
              frame.pack();
              frame.setVisible(true);
    ///   constructors
         public MyComponent()
              try
                   jbInit();
                   initTable();
              catch(Exception ex)
                   ex.printStackTrace();
    ///   protected instance methods
         protected void initTable()
              // do nor allow user interaction with calendar view
              tableView.getTableHeader().setReorderingAllowed(false);
              tableView.getTableHeader().setResizingAllowed(false);
              //tableView.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
              tableView.setRowHeight(c_RowHeight);
              // adapt all CellRenderers
              for (int i = 0; i < m_DataModel.getColumnCount(); i++)
                   TableColumn column = tableView.getColumn(tableView.getColumnName(i));
                   column.setMinWidth(c_ColWidth);
                   column.setPreferredWidth(c_ColWidth);
    ///   private instance methods
         private void jbInit() throws Exception
              this.setLayout(myLayout);
              this.add(scrollPane, BorderLayout.CENTER);
              scrollPane.getViewport().setMinimumSize(new Dimension(c_TableWidth, c_TableHeight));
              scrollPane.getViewport().setPreferredSize(new Dimension(c_TableWidth, c_TableHeight));
              tableView.setPreferredSize(new Dimension(c_TableWidth, c_TableHeight));
              addComponentListener(new MyComponent_componentAdapter(this));
    ///   event handling
         public void componentBoundsChanged(ComponentEvent e)
              scrollPane.setBounds(0, 0, getWidth(), getHeight());
              scrollPane.getViewport().setBounds(0, 0, getWidth(), getHeight());
              //tableView.setBounds(0, 0, getWidth(), getHeight());
              tableView.setSize(scrollPane.getViewport().getWidth(), scrollPane.getViewport().getHeight());
              tableView.setRowHeight(getBounds().height / 13 < c_RowHeight ?
                        c_RowHeight : getBounds().height / 13);
              System.out.println("componentBoundsChanged: getBounds() = " + getBounds());
              System.out.println("componentBoundsChanged: getSize() = " + getSize());
              System.out.println("componentBoundsChanged: getViewport().getBounds() = " + scrollPane.getViewport().getBounds());
              System.out.println("componentBoundsChanged: getViewport().getSize() = " + scrollPane.getViewport().getSize());
              System.out.println("componentBoundsChanged: tableView.getBounds() = " + tableView.getBounds());
              System.out.println("componentBoundsChanged: tableView.getSize() = " + tableView.getSize());
    ///   event adapters
    class MyComponent_componentAdapter extends ComponentAdapter
         protected MyComponent adaptee;
         MyComponent_componentAdapter(MyComponent adaptee)
              this.adaptee = adaptee;
         public void componentMoved(ComponentEvent e)
              adaptee.componentBoundsChanged(e);
         public void componentResized(ComponentEvent e)
              adaptee.componentBoundsChanged(e);
    }

    I guess i am facing exactly opposite problem.
    What i want to do is, I have nested tables in a scroll pane. So I don't want a scroll pane to show exactly whatever visible rows are there in Table (No extra space). If i expand any row, i want scroll pane to be able to show expanded.

  • Is it posiible to paging up paging down in Jtable using Default Table Model

    Hi All!
    Is it possible to do Page up and Page down in JTable using Default Tble Model?
    Kindly reply!

    yes
    it is posiible to paging up paging down in Jtable using Default Table Model. just go thru the JAVA API you will get the results.

  • Displaying JTable using GridBagLayout

    Hii Javaties
    I am displaying all my GUI using GridBagLayout Manager.
    But i dont know , how to add a JTable using GridBagLayout manager.
    I[b] want tht each column of the JTable be displayed in each cell .
    i.e column 1 should be displayed at position 1,4
    Can anybody guide me .
    Thanx

    Perhaps what you are looking for is Custom Editors or Renderers?

  • Sorting JTable using keyboard

    Hi all,
    Is it possible to sort JTable using keyboard? There is a key to get the focus to a column header by clicking the key F8. I don't find any key to sort the table based on the column which is in focus. Is there any solution for this?
    Thanks,
    Ganesh

    You miss the point of that link, there is no need to write any custom code.
    I have already tried to implement Keyboard listener of JTableHeader which must be similar to using Key Bindings.You should NOT use a KeyListener, Swing was designed to use KeyBindings
    The problem I am facing is that I am unable to find the column which got the key strokeYou don't have to write any code, the functionality you want is already supported with a Key Binding. Just use the "space" key.
    If you don't like the space key, then you can assign the Action to any other KeyStroke. The link shows you how to do that in 3-4 lines of code.

  • StackOverflowError in JTable using DefaultTableModel

    Hi:
    I have a JTable using DefaultTableModel. I also have a tableChanged function that puts values into columns based on values from other columns. Initially, I set up the table with one row, then a popup will call the addRow function on DefaultTableModel. Here's my addRow function:
    private void addRow() {
    try {
    String [] newString = new String[10];
    for (int i=0; i<10; i++)
    newString[i] = "";
    defaultTableModel.addRow(newString);
    } catch (java.lang.StackOverflowError seiou){
    As you can see from my catch statement, I keep getting a problem with a StackOverflowError when I enter values into the table; when I add a row, it kicks me out of the program. I am currently changing and checking values in the table with:
    defaultTableModel.setValueAt(); and
    defaultTableModel.getValueAt();
    Any suggestions?

    Hi:
    I have a JTable using DefaultTableModel. I also have a tableChanged function that puts values into columns based on values from other columns. Initially, I set up the table with one row, then a popup will call the addRow function on DefaultTableModel. Here's my addRow function:
    private void addRow() {
    try {
    String [] newString = new String[10];
    for (int i=0; i<10; i++)
    newString[i] = "";
    defaultTableModel.addRow(newString);
    } catch (java.lang.StackOverflowError seiou){
    As you can see from my catch statement, I keep getting a problem with a StackOverflowError when I enter values into the table; when I add a row, it kicks me out of the program. I am currently changing and checking values in the table with:
    defaultTableModel.setValueAt(); and
    defaultTableModel.getValueAt();
    Any suggestions?

  • How to assign values to JTable using mysql database

    how to assign value to JTable using mysql...

    Search the forum. You use the values of the "ResultSet" to create a "DefaultTableModel" which you then add to the "JTable".
    I'll let you pick the search keywords to use, which I've suggested above. You can also throw in my userid if you want to specifically look for my solution.

  • Jtable inside a JscrollPane - Can't see the left hand side of my Jtable (th

    Jtable inside a JscrollPane - Can't see the left hand side of my Jtable (the border)from some reason - please help. This is my code:
    public class RecordSetPanel extends JPanel {
    private JTable rsTable;
    private JScrollPane tableScrollPane;
    public RecordSetPanel() {
    setLayout(new BorderLayout());
    rsTable = new JTable();
    rsTable.setBackground(getBackground());
    rsTable.setRowHeight(25);
    rsTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    tableScrollPane = new JScrollPane(rsTable) {
    public Insets getInsets() {
    return new Insets(20, 20, 20, 20);
    tableScrollPane.setBorder(BorderFactory.createLineBorder(getBackground()));
    add(tableScrollPane, BorderLayout.CENTER);

    I've tested this code and it looks fine:
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class Dialog1
        extends JDialog {
      JPanel panel1 = new JPanel();
      BorderLayout borderLayout1 = new BorderLayout();
      public Dialog1(Frame frame, String title, boolean modal) {
        super(frame, title, modal);
        try {
          jbInit();
          pack();
        catch (Exception ex) {
          ex.printStackTrace();
      public Dialog1() {
        this(null, "", false);
      public static void main(String args[]) {
        new Dialog1().show();
      private void jbInit() throws Exception {
        panel1.setLayout(borderLayout1);
        panel1.add(new RecordSetPanel(), BorderLayout.CENTER);
        getContentPane().add(panel1);
      public class RecordSetPanel
          extends JPanel {
        private JTable rsTable;
        private JScrollPane tableScrollPane;
        public RecordSetPanel() {
          setLayout(new BorderLayout());
          TableModel dataModel = new AbstractTableModel() {
            public int getColumnCount() {
              return 10;
            public int getRowCount() {
              return 10;
            public Object getValueAt(int row, int col) {
              return new Integer(row * col);
          rsTable = new JTable(dataModel);
    //      rsTable.setBackground(getBackground());
          rsTable.setRowHeight(25);
          rsTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    //      tableScrollPane = new JScrollPane(rsTable) {
    //        public Insets getInsets() {
    //          return new Insets(20, 20, 20, 20);
    //      tableScrollPane.setBorder(BorderFactory.createLineBorder(getBackground()));
          add(new JScrollPane(rsTable), BorderLayout.CENTER);
    }

Maybe you are looking for

  • PL/SQL TABLE AS OUT ON PROCEDURE CALL AND JDBCTHIN(NEED HELP

    How can I pass pl/sql record in and out and pl/sql tables in out thru a pl/sql procedure using jdbc with the zip file of 816classes12.zip... I have tried everything I know... I know the procedure is working, others are using it with in Oracle... I ne

  • Disable Outlook Integration-Automatic Archival Feature

    Greetings, I'm trying to find a way to disable Adobe X Standard/Professional's feature of Automatic Archival of e-mail in Outlook 2010. We have a no-archiving policy in our organization, and this feature permits users to very easily circumvent the po

  • Score keeper

    I've been hired to shoot basketball games several times a week for my high school, and I need to turn around a finished product by the next day. I wanted to put in a score board or timer at the bottom of the footage I capture. I thought I could keyfr

  • Error message -3259.  Cannot download iOS 5 on Windows 7. Help please!

    My diagnosis is: Microsoft Windows 7 x64 Home Premium Edition Service Pack 1 (Build 7601) LENOVO 4311 iTunes 10.5.0.142 QuickTime not available FairPlay 1.13.35 Apple Application Support 2.1.5 iPod Updater Library 10.0d2 CD Driver 2.2.0.1 CD Driver D

  • Swedish "därför" turns out "Därför" when publishing via ftp...

    When I published the new site via ftp all the å, ä, ö letters in swedish got all messy. What do I do? Need some help to solve this... Thanks in advance!