Returns wrong row number with ENTER key in JTable...

I am having a problem to get exact row number ofJTable when ENTER key is pressed.
table.getSelectedRow() always retuns one more value when ENTER key is pressed(fired). like
if i have 5 rows in a table and when my focus is on 1st row and then i press enter key focus moves to next row and it returns 1 instead of 0 for the 1st row.
I have written a code bellow, please check it out and tell me why it happens. Please click on Add Row button for creating rows in table.
import javax.swing.*;
   import javax.swing.table.*;
   import java.awt.*;
   import java.awt.event.*;
   import java.util.Vector;
   class TableTest extends JFrame {
     MyTableModel myModel;
     JTable table;
     JButton button;
     JButton buttonQuery;
     int count = 0;
     public TableTest() {
       myModel = new MyTableModel();
       table = new JTable(myModel);
       table.setPreferredScrollableViewportSize(new Dimension(500, 200));
       JScrollPane scrollPane = new JScrollPane(table);
      table.addKeyListener(new KeyAdapter(){
          public void keyTyped(KeyEvent ke)
            if(ke.getKeyChar() == ke.VK_ENTER){
              System.out.println(table.getSelectedRow());
       getContentPane().add(scrollPane, BorderLayout.CENTER);
       getContentPane().add(button = new JButton("Add Row"),
       BorderLayout.SOUTH);
       getContentPane().add(buttonQuery = new JButton("Query"), BorderLayout.NORTH);
       button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
      Object [] aRow = new Object [8];
     String aRow1;
     for (int i=0; i<5; i++) {}
     myModel.addRow(aRow);
   buttonQuery.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent e) {
       System.out.println(myModel.getRowCount());
       System.out.println(myModel.getValueAt(1, 3));
   addWindowListener(new WindowAdapter() {
     public void windowClosing(WindowEvent e) {
       System.exit(0);
   class MyTableModel extends AbstractTableModel {
   protected final String[] headers =
   { "No", "Vehicle No", "Date of Loss", "Image Type", "Image Description", "Claim Type", "Scan Date", "User Id" };
   Vector data;
   MyTableModel() {
    data = new Vector();
   public int getColumnCount() {
     return headers.length;
   public int getRowCount() {
    return data.size();
   public Object getValueAt(int row, int col) {
   if (row < data.size() && col < 8) {
     Object [] aRow = (Object []) data.elementAt(row);
   return aRow[col];
   } else {
     return null;
   public void addRow(Object [] aRow) {
     data.addElement(aRow);
    fireTableRowsInserted(data.size()-1, data.size()-1);
   public static void main(String[] args) {
   TableTest frame = new TableTest();
   frame.pack();
   frame.setVisible(true);
   }Regards..
jaya

Dear Jaya,
I have a look at your code. And modified a bit as well to really check the getSelectedRow(). Here's the modified code: I think when key event fired, the table row is changed and then is displays the get selected row. You can check this, if you are on the last row, and you press enter, it displays 0, it means first it changes the row and then displays the selected row which is obviously rowNumber+1.
Hope it helps.
import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Vector;
class TableTest
    extends JFrame {
  MyTableModel myModel;
  JTable table;
  JButton button;
  JButton buttonQuery;
  JButton buttonSelectedRow;
  int count = 0;
  public TableTest() {
    myModel = new MyTableModel();
    table = new JTable(myModel);
    table.setPreferredScrollableViewportSize
        (new Dimension(500, 200));
    JScrollPane scrollPane = new JScrollPane(table);
    table.addKeyListener(new KeyAdapter() {
      public void keyTyped(KeyEvent ke) {
        if (ke.getKeyChar() == ke.VK_ENTER) {
          System.out.println(table.getSelectedRow());
    getContentPane().add(scrollPane, BorderLayout.CENTER);
    getContentPane().add(button = new JButton("Add Row"), BorderLayout.SOUTH);
    getContentPane().add(buttonQuery = new JButton("Query"), BorderLayout.NORTH);
    getContentPane().add(buttonSelectedRow = new JButton("Get Selected Row Number"), BorderLayout.NORTH);
    button.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        Object[] aRow = new Object[8];
        String
            aRow1;
        for (int i = 0; i < 5; i++) {}
        myModel.addRow(aRow);
    buttonSelectedRow.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        System.out.println("Selected Row is: " + table.getSelectedRow());
    buttonQuery.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        System.out.println(myModel.getRowCount());
        System.out.println(myModel.getValueAt(1, 3));
    addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        System.exit(0);
  class MyTableModel
      extends AbstractTableModel {
    protected final String[] headers = {
        "No", "Vehicle No", "Date of Loss", "Image Type", "Image Description",
        "Claim Type", "Scan Date", "User Id"};
    Vector data;
    MyTableModel() {
      data = new Vector();
    public int getColumnCount() {
      return headers.length;
    public int getRowCount() {
      return data.size();
    public Object getValueAt(int row, int col) {
      if (row < data.size() && col < 8) {
        Object[] aRow = (Object[]) data.elementAt(row);
        return aRow[col];
      else {
        return null;
    public void addRow(Object[] aRow) {
      data.addElement(aRow);
      fireTableRowsInserted(data.size() - 1, data.size() - 1);
  public static void main(String[] args) {
    TableTest frame = new TableTest();
    frame.pack();
    frame.setVisible(true);

Similar Messages

  • Submitting form with Enter key

    Hello,
    in standard html form, when you have form with submit button, the enter key when any form element is selected submits the form.
    This is very convenient for users, so I want this with UIX forms. I know it is possible (I have one form where it is working), but I can't get it working anywhere else.
    This code works:
    <uix:form method="post" name="newRoleForm">
    <uix:inlineMessage prompt="Role name">
    <uix:textInput name="newRoleName" />
    <uix:spacer width="15" />
    <uix:submitButton text="Create" formName="newRoleForm" />
    </uix:inlineMessage>
    <uix:formValue name="jboEvent" value="newRole" />
    </uix:form>
    When I copy this code to another page, it does not work...
    Can somebody help, please?

    I've studied the HTML generated by UIX and it has following bugs and misfeatures:
    1. Misfeature: Submitting with Enter works ONLY if there is exactly one text field in the form (no submit button is actually needed), as Brian Stoler wrote. I don't understand reason for this.
    2. Bug: UIX generates javascript function "_submitOnEnter" which is called as event handler for "onKeyPress" event. But this function is erroneously generated multiple times, once for each form in the page. Browsers (Mozilla and IE) use the latest implementation. This function is different for forms with one text field and for forms with more text field, but only the first one can do the job. As a consequence of this, Enter can submit the form only if the last form on a page has single text field (which is for example not the case of search form with single field above another form...)
    Tested with UIX 2.1.7 in JDeveloper 9.0.3.3, using UIX as JSP tag library.
    Workaround:
    1. Use Opera browser: it submits form with enter key even if there is no submit button (this does not work for the first text field in the form, because it has "onkeypress" event handler).
    2. Implement this feature by hand yourself, if you really need it (see below).
    3. Use accessKey: allows to submit form with Alt+<key> combination (followed by Enter with IE).
    Implementing Enter key submits with Javascript:
    1. Put the following function to the header (or to javascript library):
    function enter(e, frm) {
    var kc;
    if(window.event) kc=window.event.keyCode;
    else if(e) kc=e.which;
    else return true;
    if(kc==13) {
    submitForm(frm,1);
    return false;
    Function copied from UIX (C).
    2. Add this event handler to each input element:
    onKeyPress="return enter(event, 'formName');"
    It is obvious that this is error prone, but it works with all browsers...
    Will this be fixed in future versions?
    Why only form with one text field can be submitted?

  • How to select tree node with enter key instead of mouse click

    hia i have tree in forms 10g i can get node value when i click mouse on node but i want same with enter key which is not working any idea.
    thanx

    I'm afraid you have hit Bug 4509399
    If you have metalink access you should check Note:331369.1
    This bug has been around for the 10g R2 10.1.2.0.2 base release, which was propagated from Installing Patch 9.0.4.2 or from 10g R1 base release. You need to apply the latest patch or a one-off fix Patch 4509399
    Tony

  • Invalid Row Number with Gallery Widget

    Hi all,
    I'm having some trouble with selecting the correct gallery
    with the gallery widget. Instead of using the dropdown as shown in
    the demo, I want to use a query string for selecting the gallery.
    This is what I've done:
    <script type="text/javascript">
    function selectPortfolio() {
    var _wl = window.location.toString();
    var _pId = _wl.substring(_wl.lastIndexOf('=') + 1,
    _wl.length);
    dsGalleries.setCurrentRowNumber(_pId.toString());
    </script>
    </head>
    <body onload="selectPortfolio();">
    When I try to hit the following URL:
    my_website/portfolio.html?id=1, I'm trying to set the
    currentRowNumber to 1. When I debug through the the SpryData.js
    file I see the following function getting executed:
    Spry.Data.DataSet.prototype.setCurrentRowNumber =
    function(rowNumber)
    if (!this.data || rowNumber >= this.data.length)
    Spry.Debug.trace("Invalid row number: " + rowNumber + "\n");
    return;
    I can see rowNumber coming through as 1. However, this.data
    is coming back as null.
    Anyone see anything wrong with what I've done here?
    Sean

    Try to mkae it simple ;
    &Total=0;
    &RS_LEVEL0 = GetLevel0();
    &Row_LEVEL0=&RS.Getrow(1);
    &RS_LEVEL1=&Row.Getrowset(Scroll.JournalLine1);
    For &I=1 to &RS_LEVEL1.Activerowcount;
    &Row_LEVEL1=&RS_LEVEL1.Getrow(&I);
    &Record_LEVEL1=&Row_LEVEL1.GetRecord(Record.JournalLine1);
    &Field_LEVEL1=&Record_LEVEL1.GetField(Field.Amount);
    &Amount=&Field_LEVEL1.Value;
    &Total=&Total + &Amount;
    end-for;
    Your_Level_0_Record_Name.LEVEL_0_TOTAL_FIELD_NAME.value=&Total;
    Hope it will work!!!
    Don't do any declearation it will automaytically decleared.
    Thanks,
    Amit

  • Submitting a form with enter key causing strange problems

    I am having a very strange problem with a webapp I am currently developing. I am using JSF 1.2 along with Facelets and RichFaces. I have coded a workflow/wizard 4-step process, and on some pages I have 4 submit buttons that all call different actions on the page. The users thought it would be useful to have the enter key submit the form, so I followed some online resources to trap a keypress using javascript, looking for the enter keycode and calling document.getElementById("elementName").click(). This works fine most of the time. Sometimes, though, it seems as if an entire new session is being created, and odd behavior starts happening. For example, my page will only include 2 of the 4 facelets on the screen -or- I will get NullPointerExceptions for objects that I know have been created in the session bean I am currently using -or- I will get a duplicate form Id after trying to re-submit the page. Could the javascript click simulation not be submitting all of the form elements or is the enter key also acting like its default action (the form submission) in addition to the "click"? I'm really at my wit's end here (plus it's nearly 3 AM, that never helps things). All of the buttons being clicked are standard h:commandButtons. There is some setTimeout logic included to disable the buttons on the page to prevent double clicks (I cannot disable them onsubmit because disabled buttons don't pass the right values, perhaps that's causing it, but if so, clicking the buttons with the mouse would cause that issue too, right?)
    I am not posting the code (yet), but if anyone wants to take a look see and see if I am doing something really abhorrently wrong, I'm more than willing to, I'm just curious if anyone has had problems regarding javascript submission of forms via the click() method. Clicking the button does not exhibit this type of behavior. Just as a side note: I am doing different things with the enter key depending if a modal window is open (the enter key closes the modal if it's up, and if not, it submits the form via a button click).
    Any help is much appreciated, if anyone has any inkling about where I should start looking for answers it would be really helpful.
    Thank you.

    edfrost wrote:
    Could the javascript click simulation not be submitting all of the form elements or is the enter key also acting like its default action (the form submission) in addition to the "click"?My guess is the second of these. You need to suppress the event handling after programmatically clicking the button.

  • Multi line field Navigation problem with ENTER key

    No trigger on the field. Multi line Property is set to true.
    The probleb is, when the cursor reaches in the multi line field. the contents of the field are hilighted/selected. So as it happens in Notepad or Word, if you select some already written text and press ENTER key the selected text will be replaced by carriage return so the selected data will be lost. Same is the case with multi line field. When field gets focus it selects the contents of field and when ENTER is pressed all the contents are deleted and a carriage return is placed.
    any solution?
    null

    Hi Nadeem,
    One work around is that you have store content of that multi-line field in to some other variable thru PRE-TEXT-ITEM and once again assign (based on some conditon) in POST-TEXT-ITEM.
    null

  • Problem with Enter key on Aluminum Keyboard

    Just upgraded to an Aluminum iMac with the thin keyboard. We have a terminal application that communicates with our mainframe. The application looks for the 0x03 character, along with the NSNumericPadKeyMask flag, to determine that the Enter key was pressed, and then changes the character to a 0x0d (Return). This is because the 0x03 character is recognized as a Break key on the mainframe. However, when using the Aluminum Keyboard, the Enter key goes straight through as a 0x03, meaning the flag is not being set. To make things more interesting, if I use the Keyboard Viewer and click on the Enter key, the flag is set and the 0x0d is sent.
    Is there something else I should be looking for to recognize the Enter key? Perhaps something with the KeyCode? Is there some way to remap the Enter key to emulate the Return?

    I don't think you'll be able to control a Button symbol in the way you desire.  You probably need to create it as a MovieClip so that you can control what frame it is in.
    To utilize the ENTER key to take action, the following should work...
    var keyListener:Object = new Object();
    keyListener.onKeyDown = function() {
        if (Key.isDown(Key.ENTER)) {
             // do your button_mc control here
    Key.addListener(keyListener);

  • JTable row selection with tab key

    Helo.
    I'm having a problem selecting rows in a JTable. The JTable is with single row selection and without column and cell selection. When I press <tab> the selection changes to another cell, and I wanna it to change to the other row of the table, can anyone help me? I think this is a easy one and I haven�t found a way to do it. I�m using JBuilder for the development.

    The default Action for the Tab KeyStroke is to move focus to the next cell.
    The default Action for the Enter KeyStroke is to move focus to the next line.
    So this functionality is already available in JTable by default.
    If you want to Tab Key to work the same way as the Enter Key then you need to map the Tab Key to use the Action assigned to the Enter Key.
    This [url http://forum.java.sun.com/thread.jsp?forum=57&thread=505866]posting shows how you can reassign an Action for a given KeyStroke.
    For more information on this topic read this section from the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/misc/keybinding.html]How to Use Key Bindings.

  • Problem with Enter key and JOptionPane in 1.4

    Hi,
    I had a problem with an application I was working on.
    In this application, pressing [Enter] anywhere within the focused window would submit the information entered into the form that was contained within the frame.
    The application would then try to validate the data. If it was found to be invalid, it would pop up a JOptionPane informing the user of that fact.
    By default, pressing [Enter] when a JOptionPane is up will activate the focused button (in most cases, the [OK] button) thus dismissing the dialog.
    In JDK 1.3 this worked fine. But in JDK 1.4, this has the result of dismissing the dialog and opping it up again. This is because the [Enter] key still works on the frame behind the JOptionPane and thus tries to validate it again, which results in another invalid dialog msg popping up.
    The only way to get out is to use the mouse or the Esc key.
    Now, in the application I put in a workaround that I was not very happy with. So, to make sure it wasn't the application itself, I created a test which demonstrates that it still misbehaves.
    Here it is.
    import java.awt.Container;
    import java.awt.FlowLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.KeyEvent;
    import javax.swing.AbstractAction;
    import javax.swing.JButton;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JOptionPane;
    import javax.swing.JTextField;
    import javax.swing.KeyStroke;
    import javax.swing.UIManager;
    import javax.swing.UnsupportedLookAndFeelException;
    import javax.swing.WindowConstants;
    * @author avromf
    public class FocusProblemTest extends AbstractAction
         private static JFrame frame;
         public FocusProblemTest()
              super();
              putValue(NAME, "Test");
         public void actionPerformed(ActionEvent e)
              JOptionPane.showMessageDialog(frame, "This is a test.");
         public static void main(String[] args)
              FocusProblemTest action= new FocusProblemTest();
              try
                   UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
              catch (Exception e)
                   e.printStackTrace();
              frame= new JFrame("Test");
              frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
              Container contents= frame.getContentPane();
              contents.setLayout(new FlowLayout());
              JTextField field= new JTextField("Test");
              field.setColumns(30);
              JButton  button= new JButton(action);
              KeyStroke enterKey = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, true);
              button.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(enterKey, "test");
              button.getActionMap().put("test", action);
              contents.add(field);
              contents.add(button);
              frame.pack();
              frame.setVisible(true);
    }Does anyone have any solution to this problem?

    I know that focus management has changed alot.
    Based on my experimentation a while back, in 1.4 it still believes that the JFrame is the window in focus, even though a JOptionPane is currently in front of it (unless I misinterpreted what was going on). Thus, the frame seems to get the keyboard event and re-invoke the action.
    A.F.

  • Submit a Form in IE with Enter key.

    Hi all,
    I have a Form with a Get attribute, a textfield and a search
    (submit) button.
    When I press the Enter key in my keyboard, the form is not
    submited in I.E. (i'm using IE 7).
    When I click the button with the mouse, it works.
    In Firefox, all (keyboard and mouse) works.
    How can we workaround this issue?
    Thanks

    oicram wrote:
    > Please, I need an answer here. I have deeply search over
    the internet and I only found something about .js or hidden fields,
    but its all vague...
    http://www.webreference.com/programming/java_dhtml/chap8/2/2.html
    David Powers, Adobe Community Expert
    Author, "The Essential Guide to Dreamweaver CS3" (friends of
    ED)
    Author, "PHP Solutions" (friends of ED)
    http://foundationphp.com/

  • How can i select the next column instead of next row when press enter key

    I need to know how can i select the next column instead of next row when i press the enter key.By default ,when i press enter key the next row is selected and the column remain unchanged but I wants opposite that is the row should remain unchanged but column index will changed.
    Thanks to all.

    Well, the right arrow key will already move you to the next column, so the easiest way to do this is to modify the InputMap to have the Enter key invoke the same Action as the right arrow key.
    You can search the forum for my "Table Actions" (without the space) example that will show you how to do this.

  • Calculating the row number with DAX

    Hello,
    Can somebody help me to obtain the row number in a calculated column using DAX (PowerPivot 2013) ?
    I do not have any column that would contain unique values (would be easy in that case !). I just want to obtain a different value in each row.
    Thank you.

    Hi DP17000,
    According to your description, you need to add a column with the RowNumber to your Pivot table by using DAX, right?
    Based on my tested, we can use a ranks function to achieve your requirement.
    =RANKX(case0305,[amount],[amount],0,dense)
    Reference
    https://msdn.microsoft.com/en-us/library/gg492185.aspx?f=255&MSPPError=-2147217396
    http://ayadshammout.com/2013/02/19/dax-rankx-function-scenarios/
    Regards,
    Charlie Liao
    TechNet Community Support

  • Navigation in multi row field using ENTER key

    Contents of the field are deleted when I use ENTER key in a multi line field.
    Any solution?

    <BLOCKQUOTE><font size="1" face="Verdana, Arial">quote:</font><HR>Originally posted by Nadeem Ameer ():
    Contents of the field are deleted when I use ENTER key in a multi line field.
    Any solution?<HR></BLOCKQUOTE>
    the normal that when you press an Enter key
    in a field which is a multi line field the cursor is moving to the next line.
    sol:verify that you don't write any wrong code in the key-enter trigger
    & check that you set the multi_line property of that item to yes.
    null

  • Repeat last command with enter key in dbx

    I am using dbx 7.7 on Solaris 10 (Sun Studio 12.1). Is it possible to configure dbx so that pressing the <enter> key will always repeat the previos command? for instance, if i do one "next" command, i want consequent <enter> key-presses to do "next", until i explicitly execute a different command.
    Thanks,
    Yael

    yaelfrommer wrote:
    Hello Jean,
    Thanks for this advice, i started working with dbxtool and it's very nice.
    2 questions:
    1. The Function keys (F7, F8, etc.) don't work, any idea what could be the problem?There is a bug in the dbx cmdio window where it ignores F-key. It doesn't even have
    a decent context menu. You should be able to get F7 etc working by moving the
    focus elsewhere, like the editor window.
    2. In the default .dbxrc file there's a line "button ignore step up" to "add `step up' button to GUI", but no button was added. Is there anything else i should do to make this work?
    These are really old. (we should remove them from the default .dbxrc!)
    The current way to add a button is via Debug->NewDbxButton
    Thanks,
    Yael

  • Submit OA page with Enter key in custom page

    Hello All,
    I have one custom page with 20+ fields and two submit buttons to do different processing.
    On this page, if enter key is pressed then I need to submit the form i.e. invoke processing corresponding to one of the submit button.
    I know that at field level I can bind enter key event. But for that I need to write same code 20 times for all 20 fields.
    Do we have any simple way to implement submit if enter key is pressed in any of the fields?
    Any help will be highly appreciated.
    Thanks,
    Ritesh

    Hi Ritesh,
    Not sure but you will want to try implementing the method mentioned by Anil using "OAPageLayoutBean" to get the enter key handle for all the fields in a page.
    i.e. try with
    OAPageLayoutBean page = pageContext.getPageLayoutBean();
    Hashtable params = new Hashtable(); 
        params.put ("Go", "value1");
        page.setAttributeValue(OAWebBeanConstants.ON_KEY_PRESS_ATTR, new OABoundValueEnterOnKeyPress(pageContext,
                                          "DefaultFormName", // enclosing form name
                                          params, // request parameters
                                          false, // client unvalidated
                                          false)); // server unvalidatedinstead of
    OAMessageTextInputBean HelloName = (OAMessageTextInputBean)webBean.findChildRecursive("HelloName");
             Hashtable params = new Hashtable(); 
             params.put ("Go", "value1");
             HelloName.setAttributeValue(OAWebBeanConstants.ON_KEY_PRESS_ATTR,
             new OABoundValueEnterOnKeyPress(pageContext,
                                          "DefaultFormName", // enclosing form name
                                          params, // request parameters
                                          false, // client unvalidated
                                          false)); // server unvalidatedand pls update the result.
    regards,
    Anand

Maybe you are looking for

  • 9i OEM Jobs Won't Complete

    Hello Everyone. I have a 9i OEM repostitory on Windows 2003 server. The Repository was originially on a windows NT server. I moved the repository and created OMS and agent on the new server and everything came up properly. Agent pings to the console

  • "Itunes has stopped updating your podcast" message -- is there away around?

    When new podcasts are downloaded into Itunes, I transfer them straight to my ipod. I don't play them in Itunes. As a result, I have to tell Itunes that I DO want to continue downloading new files - for every podcast to which I subscribe, on a recurri

  • About wls6.0 servlet mapping

              I do the wls6.0 servlet,I copy wls example helloservletExample in           the mydomain\application\DefaultWebApp_myserver\web-inf\clsses\           and modify the xml file           <?xml version="1.0" ?>           <!DOCTYPE web-app PUBLI

  • Why not index every field in a database

    Hello, I hope this is not to much of a newbie question. We have a database that is being used by an application. We do not know which fields are queried on, the application allows for any/all field(s) to be searched on. Obviously, we can know which f

  • Microsoft JVM vs Sun JVM

    We have an application that requires only Microsoft Java VM be running in our IE browsers, so we cannot run Sun Java VM at the same time. Is there a workaround that will allow users to view Discoverer output? I am still investigating utilizing Discov