Listen double clicks on JTable's row

hi,
I want to know how to catch double clicks did on a specific JTable's row, or any cell on that.
I know that's possible because JTable is a JComponent..so, I want to know how to catch the event when the user press Enter over a single selected row, too...
If you may show me and example or specific links, I'll thank you so much..
lucky..

b) The Enter key is used to move the row selection to
the next row so you need to override the default
mappings of the table.
This posting shows how you would do the above on a
JList. The code should be similiar for a JTable.
http://forum.java.sun.com/thread.jspa?forumID=57&threa
dID=626866Thanks anyway...I fix that with a tricky and simplest solution.
I only put a KeyEventListener on the table and catch the keyEvent, and if it's a EnterKey, then check wich row is selected on table.
table.addkeyListener(new KeyListener(){
            public void keyPressed(KeyEvent e) {
                if(e.getKeyCode()==KeyEvent.VK_ENTER){
                    int[] selected_rows = table.getSelectedRows();
                    if(selected_rows.length==1){
                        int row = selected_rows[0];
                        DefaultTableModel table_model = (DefaultTableModel)table.getModel();
                        Object element_at_row = directory_model.getValueAt(row, 1); //I wanna Only the element at column 1
                         //do more things...                      
//....other interface's methods..
);

Similar Messages

  • Problem while displaying the data when double clicked on JTable element

    Hi All,
    i have one List box( JList ) and one table (JTable). Both JTable and JList are positioned on the same Frame. I am able to drag the elements from JList to JTable and also i have added the mouse click action on both List box and JTable.
    if i double click on JList element, that will popup one dialog box.
    if i double click on JTable cell element that was dragged from JList, that will popup same dialog box which was opened earlier for JList action.
    But my problem here is:
    Suppose if i drag the four elements one by one from JList to JTable and (after four elements dragged) double clicked the first element which was dragged first that displayed the popup dialog box structure correctly but the data displayed in that was not correct. It is showing the data of recent dragged element( i.e, fourth element).
    But if i double click on JList element that is showing the correct data according to the double clicked element.
    What might be the problem here, why it was not displaying the correct data when double clicked on JTable element.
    Please help me here.
    Many thanks in advance.
    The following code is used in mouse clicked event method of JList
    private void listMouseClicked(java.awt.event.MouseEvent evt) {                                              
             if(evt.getClickCount()==2){
             AssigningResourcesUI assignResource=new AssigningResourcesUI(this,true);
             assignResource.show();
    }                AND The following code is used in mouse click enevet method of JTable.
    private void tableMouseClicked(java.awt.event.MouseEvent evt) {                                          
            if(evt.getClickCount()==2){
             int row=table.rowAtPoint(new Point(evt.getX(), evt.getY()));
             int col=table.columnAtPoint(new Point(evt.getX(), evt.getY()));
             if(row==-1||col==-1){
                 return;
              Object obj=table.getModel().getValueAt(row, col);
             if(obj==null||(obj.equals(""))){
               }else{
             AssigningResourcesUI assignResource=new AssigningResourcesUI(this,true);
             assignResource.show();
         }            Thanks & Regards,
    Maadhav....
    Edited by: maadhav on Jul 1, 2009 7:22 AM

    I doubt it is related to your problem but:
    int row=table.rowAtPoint(new Point(evt.getX(), evt.getY()));Why are you creating a new Point? Just use evt.getPoint().
    Object obj=table.getModel().getValueAt(row, col);Don't get the data through the model method, get the data through the table method:
    Object obj = table.getValueAt(...)
    This way it will work even if the table happens to be sorted.
    Instead of creating a AssigningResourcesUI object, just disply the value retrieved from the model. That way you know whether the problem is with the mouse event code or your UI class. Like Walter suggested above I"m guess the problem is with your UI class.

  • Mouse Double Click on JTable

    I'm having difficulty seeing how to capture a double-click event from a
    JTable. I can't find the correct listener interface in order to get
    this event (ActionListener is not available for this component).
    you can contact me at
    [email protected]
    null

    hi,
    i tried
    if (event.getClickCount() == 2){
    int row =jTable1.rowAtPoint(event.getPoint());
    if (row != -1) {
    // double click processing here
    in the click event.
    it didn't work.
    any idea???
    <BLOCKQUOTE><font size="1" face="Verdana, Arial">quote:</font><HR>Originally posted by Sathish:
    Hi,
    Did you try addMouseListener() ?
    If you are using the GridControl, use getTable().addMouseListener()
    Tx<HR></BLOCKQUOTE>
    null

  • Overriding double click in JTable custom cell

    I have a JTable where I reset the custom cells to become editable on a single click instead if a double using:
    ((DefaultCellEditor)table.getDefaultEditor(String.class)).setClickCountToStart(1);
    Now what I need to do is display a JPopupMenu click a cell is double clicked. This works on cells that are not editable but the problem is that the user needs the popup dialog to display info for the cells that are editable.
    I have used the basic way to implement a double click on a certain column (in this case my third column):
    public void mouseClicked(MouseEvent e){
                   if (e.getClickCount() == 2 && table.getSelectedColumn() == 2 ){
                        popupMenu.show( e.getComponent(),
    e.getX(), e.getY() );
    But when double clicking, nothing happens.
    Anyone have any idea to implement this or over-ride an editable cell?
    Thanks,
    Chris

    This still says <identifier> expect, how can I resove this please? Then you still have something wrong with your code. Since you didn't post your code how are we supposed to help?
    The proper way to ask a question is to include your demo code that trys to illustrate the problem. Something like the following:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class TableRightClick extends JFrame
         public TableRightClick()
              JTable table = new JTable(10, 5);
              table.addMouseListener( new MouseAdapter()
                   public void mousePressed(MouseEvent e)
                        if ( SwingUtilities.isRightMouseButton(e) )
    //                    if (e.isPopupTrigger())
                             JTable source = (JTable)e.getSource();
                             int row = source.rowAtPoint( e.getPoint() );
                             int column = source.columnAtPoint( e.getPoint() );
                             System.out.println(column);
                             source.changeSelection(row, column, false, false);
              table.setPreferredScrollableViewportSize(table.getPreferredSize());
              getContentPane().add( new JScrollPane(table) );
         public static void main(String[] args)
              TableRightClick frame = new TableRightClick();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.pack();
              frame.setLocationRelativeTo( null );
              frame.setVisible( true );
    }

  • Double click in alv report rows

    Hi to all!!
    I have an alv report and I want it to go directly to a transaction IW38 when I double click the row, I know that i have to use the reuse_alv_grid_display's IT_EVENT parameter and also the I_CALLBACK_USERCOMMAND but I don't know exactly how.
    Can anybody show me an example or help me?
    THANKS A LOT!!!

    Hi,
    Take a look at the following code ( 2 main perform ):
    *       ITAB_user_command                          *
    FORM itab_user_command  USING ucomm TYPE sy-ucomm
                            s_selfield TYPE slis_selfield.
      CASE ucomm.
        WHEN '&IC1'.
    *     Call Transaction MM03
          IF s_selfield-fieldname = 'MATNR' .
           READ TABLE t_bom INDEX s_selfield-tabindex.
            SET PARAMETER ID 'MAT' FIELD t_bom-matnr.
            CALL TRANSACTION 'MM03' AND SKIP FIRST SCREEN.
          ENDIF.
      ENDCASE.
    *&      Form  display_data
    FORM display_data.
      CALL FUNCTION 'REUSE_ALV_GRID_DISPLAY'
           EXPORTING
    *           i_background_id             = 'SIWB_WALLPAPER'
                i_background_id             = 'ALV_BACKGROUND'
                i_callback_program          = w_repid
    *           i_callback_html_top_of_page = w_html_top_of_page
    *           i_structure_name            = 'TRDIR'
                i_bypassing_buffer          = 'X'
                i_default                   = 'X'
                i_save                      = w_variant_save "'A'
                is_variant                  = w_variant
                is_layout                   = w_layout
                i_callback_user_command     = 'ITAB_USER_COMMAND'
    *            i_callback_pf_status_set    = 'SET_PF_STATUS'
                it_fieldcat                 = i_fieldcat_alv[]
                it_events                   = i_events[]
                it_event_exit               = i_event_exit[]
    *            it_excluding                = i_excluding
                is_print                    = w_print
    *           i_screen_start_column       = 1
    *           i_screen_start_line         = 1
    *           i_screen_end_column         = 70
    *           i_screen_end_line           = 30
           TABLES
                t_outtab                    = t_bom
           EXCEPTIONS
                program_error               = 1.
    ENDFORM.                    " display_data
    Best regards,
    Erwan

  • Agentry - Disable Double Click Action on Individual Row

    Is it possible to disable the double click action on a single row in a list screen?  I wanted to have a rule that would disable a row if it has already been updated.  Let me know if that is possible.

    The double click option can not be set by a rule or not, but the action is called, you can put an enable rule on to check the data already.
    Stephen

  • Mouse Double Click on an editable cell of JTable

    Hi Pros:
    Maybe this is an old question but no answser from Forum.
    I have a JTable with adding MouseListener. I tried to put double click behavior on nay row in the table. The problem was that this action can obly work on the uneditable cell and do not work on editable cell.
    Anyone have ideas and help me.
    Thank you!

    Hi Wang,
    I have a problem similar to the one you have some time back.
    I have a query for which I need to use PreparedStatement .The query runs likes this :-
    String str = " Select ? , ename from emp where deptno ? ";
    The values of ? need to be assigned dynamically.
    But I cannot create Prepared Statement from this query .
    If you have got answer to your questions can you inform me at
    [email protected]
    Thanks in advance

  • How to process double click on rows of data displayed on html page?

    I need to display rows of data so that user could double click on a particular row to get more details.
    What I could think of doing is to embed an applet with a JTable that could easily process double click event. But the issues I have are:-
    1. I am not able to pass the data (the jsp got from processing some javabeans) to be displayed on the applet's table. It seems the applet needs to get loaded on the user's browser first and then the applet could ask the server (servlet / jsp) to send the data.
    Is there any way to provide data to applet other than html's parameter/value pairs?
    2. As per design, this applet should be used only to display the content. Double click on a row would only open a browser window to display the entire details of the data; there should not be any interaction with the server.
    Is there a better, more elegant way of doing this?
    Thanks.

    I posted a thread on Applet servlet communication here:
    http://forum.java.sun.com/thread.jsp?forum=33&thread=205887
    It uses the ObjectOutput/InputStream so you can send serializable objects rather than just text.
    Cheers,
    Anthony

  • ***How to Invoke backing bean method by DOUBLE-CLICK the table ROW!!***

    Hi,
    How can I collect the selected row value & navigate to next page by DOUBLE-CLICK the result table row.
    My application got searchResult page where I am displaying the list of user in result table. Then selecting any one row and navigating to master details page by clicking the continue button. Button Action method will collect the selected row userID which I am forwarding to the masterDetails page.
    Same functionality I want to do by double click the row instead of clicking the button!!. I want to trigger the backing bean method if the user double click the row basically. Please help me in this how to do this?
    Current button action method:
    *public String userSelected() {*
    FacesCtrlHierNodeBinding binding = (FacesCtrlHierNodeBinding) searchResultTable.getSelectedRowData();
    currentRow = binding.getRow();
    selectedNetID = (String) currentRow.getAttribute("netid");
    System.out.println("selectedNetID -->"+selectedNetID);
    requestContext.getPageFlowScope().put("netid",selectedNetID);
    return "continue";
    *}*

    Puthanampatti ,
    Yes, I am using the same. Below is my code. I am trying to get the object of the MAIN jspx page region (where I am displaying the fragments) and refresh the one. But cant able to get the object for the region it is returning null. without refresh seems the navigation wont work.
    public void doDbClick(ClientEvent clientEvent) {
    FacesCtrlHierNodeBinding binding = (FacesCtrlHierNodeBinding) searchResultTable.getSelectedRowData();
    currentRow = binding.getRow();
    selectedNetID = (String) currentRow.getAttribute("netid");
    System.out.println("selectedNetID -->"+selectedNetID);
    requestContext.getPageFlowScope().put("netid",selectedNetID);
    try{
    FacesContext facesCtx = FacesContext.getCurrentInstance();
    NavigationHandler nh = facesCtx.getApplication().getNavigationHandler();
    nh.handleNavigation(facesCtx, "", "continue");
    System.out.println("region obj -->" +facesCtx.getViewRoot().findComponent("advse1"));
    // Refresh the current region; advse1 is the id of the region component inside jspx page
    AdfFacesContext.getCurrentInstance().addPartialTarget(facesCtx.getViewRoot().findComponent("advse1"));
    catch(Exception e){
    System.out.println("Error is: " +e);
    Is this correct coding to get the region object?? actually the "result table" and "Master details" are 2 different fragments which are linked with task-flow and the task flow is part of main jspx page as a region. I am using that region ID to get the obj, but cant able to get so....!!! any idea

  • Make Double Click event on Row, Matrix

    Hi All,
    I'm new in SDK and sorry for my English.
    Please show me how to make double click event on Row of  Matrix, i have created a table contain all Draft which Docstatus is open and order by ObjType(DocType), but i can't using Link Button on DocNum Column to view Object Detail . I think another way to do that is make a double click event on each row of matrix. Can I do like that ? plz show me . Thank for any suggestion.
    Thanks

    Hi Shafi,
    This is my .srf file
    <items><action type="add"><item uid="MTX_Data" type="127" left="15" tab_order="0" width="620" top="41" height="285" visible="1" enabled="1" from_pane="0" to_pane="0" disp_desc="0" right_just="0" description="" linkto="" forecolor="-1" backcolor="-1" text_style="0" font_size="-1" supp_zeros="0" AffectsFormMode="1"><AutoManagedAttribute /><specific SelectionMode="2" layout="0" titleHeight="19" cellHeight="19" TabOrder="0">
    This is my code draw a form with matrix
    Private Sub DrawForm()
            Try
                'Read File interface
                LoadFromXML("DraftOpen.srf")
            Catch ex As Exception
                MessageBox.Show(ex.Message)
            End Try
            oForm = SBO_Application.Forms.Item("DRFOPEN")
            ' Add Items       
            ' Add a matrix
            oMatrix = oForm.Items.Item("MTX_Data").Specific
            oMatrix.SelectionMode = SAPbouiCOM.BoMatrixSelect.ms_Single
    This is my event
    Private Sub SBO_Application_ItemEvent(ByVal FormUID As String, ByRef pVal As SAPbouiCOM.ItemEvent, ByRef BubbleEvent As Boolean) Handles SBO_Application.ItemEvent
            If pVal.FormUID = "DRFOPEN" And pVal.ItemUID = "MTX_Data" And pVal.EventType = SAPbouiCOM.BoEventTypes.et_DOUBLE_CLICK And pVal.BeforeAction = True Then
                Try
                    oForm = SBO_Application.Forms.Item("DRFOPEN")
                    Dim omatrix As SAPbouiCOM.Matrix
                    omatrix = oForm.Items.Item("MTX_Data").Specific
                    If omatrix.RowCount > 0 Then
                        For i As Integer = 1 To omatrix.RowCount
                            If omatrix.IsRowSelected(i) = True Then
                                MessageBox.Show(omatrix.Columns.Item(1).Cells.Item(pVal.Row).Specific.value)
                                MessageBox.Show(omatrix.Columns.Item(2).Cells.Item(pVal.Row).Specific.value)
                            End If
                        Next
                    End If
                Catch ex As Exception
                    SBO_Application.MessageBox(ex.Message)
                End Try
            End If
    please help me to check this code. i don't know why it's still not working with double click event. sorry to disturb you.
    Edited by: PeterHoang on Aug 30, 2011 10:15 AM

  • Double click functionality in Webdynpro ABAP ALV

    Hello!
    I have web dynpro application with ALV Table.
    I need to reproduce the standard R/3 functionality: after the double clicking on the table row the new window with content of that row's fields should appear in the form layout .
    For example, such functionality we have in the RSDMD transaction.
    So I have two questions:
    1. How to catch double click in the alv table of the  Web dynpro application;
    2. How to represent information from the alv table row in the form layout?
    Could you please help me?
    Thanks,
    Mariya

    Hi Maria,
    Say suppose I am displaying the information from SFLIGHT in an ALV format & when I click on any 1 row's CARRID I would like to fetch the corresponding BOOKING details for that particular combination of CARRID, CONNID & FLDATE then I can proceed as follows:
    1) Make the CARRID cell of your ALV to appear as an LinkToAction
    2) Create an event handler for the ON_CLICK event of the ALV & within this event handler fetch the information about the row's CARRID, CONNID & FLDATE. Call a popup window and display the corresponding information in this row.
    Below is the code to make your CARRID field as an LinkToAction:
    METHOD wddomodifyview .
      wd_this->build_alv( ).
    ENDMETHOD.
    METHOD build_alv .
      DATA:
        lr_alv_usage       TYPE REF TO if_wd_component_usage,
        lr_if_controller   TYPE REF TO iwci_salv_wd_table,
        lr_config          TYPE REF TO cl_salv_wd_config_table,
        lr_column_settings TYPE REF TO if_salv_wd_column_settings,
        lt_columns         TYPE        salv_wd_t_column_ref,
        lr_link            TYPE REF TO cl_salv_wd_uie_link_to_action,
        lr_checkbox        TYPE REF TO cl_salv_wd_uie_checkbox,
        lr_image           TYPE REF TO cl_salv_wd_uie_image.
      FIELD-SYMBOLS
        <fs_column> LIKE LINE OF lt_columns.
    * Instantiate the ALV Component
      lr_alv_usage = wd_this->wd_cpuse_alv( ).
      IF lr_alv_usage->has_active_component( ) IS INITIAL.
        lr_alv_usage->create_component( ).
      ENDIF.
    * Get reference to model
      lr_if_controller = wd_this->wd_cpifc_alv( ).
      lr_config        = lr_if_controller->get_model( ).
    * Set the UI elements.
      lr_column_settings ?= lr_config.
      lt_columns = lr_column_settings->get_columns( ).
      LOOP AT lt_columns ASSIGNING <fs_column>.
        if <fs_column>-id = 'CARRID'.
          CREATE OBJECT lr_link.
          lr_link->set_text_fieldname( <fs_column>-id ).
          <fs_column>-r_column->set_cell_editor( lr_link ).
        ENDif.
      ENDLOOP.
    ENDMETHOD.

  • Opening humantask in BPM WorkSpace with double click runs 2 instances

    Hello BPM experts,
    I have this standard scenario:
    User opens a task by double clicking on a task row in BPM Workspace task list. Then the task is opened both in popup and in the worspace window (below the task list table).
    My question is how can I make workspace open only 1 form instance?
    Example:
    -double click would open only popup with form in it (no task is opened under the worklist)
    -single click would open only form in bpm workspace window (as it is now)
    Any ideas and help is appreciated!

    Hi,
    Why do you double click on it??
    Anyway that is the way it is..
    I thought it is opening two different windows.
    just click once and you should be able to see only in the bottom part of the same window.
    If you double click it will open another window and it will show in the bottom part also.
    Hope helps ...
    Thanks,
    nir

  • Double Click event on table

    I need to allow selection of table row on double click - I implemented this functionality as suggested in article "http://technology.amis.nl/blog/3845/adf-11g-richfaces-handling-the-client-side-double-click-to-invoke-a-server-side-operation". I noticed the double click works fine if I click on any part of the row that is empty (without text). If i double click on the text that is displayed on the column cell - it just highlights the text and does not invoke Java script method for handling double-click event. I have set table 'rowselection' to 'single'. I am using Jdeveloper 11.1.5 and Firefox (3.1.16) browser.
    Any one else has experienced this issue, is there any solution for this.

    Thanks Timo for your response. I am seeing this odd behavior when using pageflowscope managed bean.
    1). I have a page (part of unbounded taskflow) that has commandlink which invokes a task flow as dialog (inline-popup):
    <?xml version='1.0' encoding='UTF-8'?>
    <jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="2.1"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:af="http://xmlns.oracle.com/adf/faces/rich">
    <jsp:directive.page contentType="text/html;charset=UTF-8"/>
    <f:view>
    <af:document id="d1" title="testw">
    <af:form id="f1">
    <af:panelGroupLayout id="pgl1">
    <af:commandLink text="Link"
    id="cl1" useWindow="true"
    immediate="true"
    windowHeight="500" windowWidth="600"
    windowEmbedStyle="inlineDocument"
    inlineStyle="text-align:left;"
    action="testflow"/>
    </af:panelGroupLayout>
    </af:form>
    </af:document>
    </f:view>
    </jsp:root>
    2). The inline popup has a table where I am using double click event on a row.
    <?xml version='1.0' encoding='UTF-8'?>
    <jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="2.1"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:af="http://xmlns.oracle.com/adf/faces/rich">
    <jsp:directive.page contentType="text/html;charset=UTF-8"/>
    <f:view>
    <af:document id="d1">
    <af:form id="f1" clientComponent="true">
    <af:table value="#{TestdblClick.list}" var="row"
    rowBandingInterval="0" id="t1" rowSelection="single"
    clientComponent="true" binding="#{TestdblClick.contactTable}"
    emptyText="no data" columnStretching="last">
    <af:clientListener method="dblkfunction" type="dblClick"/>
    <af:serverListener type="doubleClickOnRow"
    method="#{TestdblClick.doubleClick}"/>
    <af:clientListener method="singlelkfunction" type="selection"/>
    <af:serverListener type="singleClickOnRow"
    method="#{TestdblClick.singleClick}"/>
    <af:column sortable="false" headerText="Col1" align="start" id="c3"
    rowHeader="unstyled">
    <af:outputText value="#{row.col1}" id="ot1"/>
    </af:column>
    <af:column sortable="false" headerText="Col2" align="start" id="c2">
    <af:outputText value="#{row.col2}" id="ot3"/>
    </af:column>
    <af:column sortable="false" headerText="Col3" align="start" id="c1">
    <af:outputText value="#{row.col3}" id="ot2"/>
    </af:column>
    </af:table>
    </af:form>
    <f:facet name="metaContainer">
    <af:resource type="javascript">
    function dblkfunction(event) {
    var source = event.getSource();
    AdfCustomEvent.queue(source, "doubleClickOnRow",
    },false);
    function singlelkfunction(event) {
    var source = event.getSource();
    AdfCustomEvent.queue(source, "singleClickOnRow",
    false);
    </af:resource>
    </f:facet>
    </af:document>
    </f:view>
    </jsp:root>
    TestdblClick.java
    ====================
    public class TestdblClick {
    public TestdblClick() {
    private RichTable contactTable;
    private List<Testdata2> list = null;
    public List<Testdata2> getList() {
    this.list = new Vector<Testdata2>();
    Testdata2 t1 = new Testdata2 ("joe", "demaggio", "contact");
    Testdata2 t2 = new Testdata2 ("joe2", "demaggio2", "contact");
    Testdata2 t3 = new Testdata2 ("joe3", "demaggio3", "contact");
    list.add(t1);
    list.add(t2);
    list.add(t3);
    return list;
    public void setList(List<Testdata2> list) {
    this.list = list;
    public void singleClick(ClientEvent clientEvent)
    System.out.println("------single click------");
    public void doubleClick(ClientEvent clientEvent)
    System.out.println("------doubleclick------");
    public void setContactTable(RichTable contactTable) {
    this.contactTable = contactTable;
    public RichTable getContactTable() {
    return contactTable;
    If I make "TestdblClick" managed bean as request scope to handle double-click event it works fine, however if I make "TestdblClick" managed bean as pageflow scope (task flow) it does not work when double click is on a text within the table row. I am not sure why pageflowscope should impact the double-click behavior.

  • Double click on a JTable row.

    I got and run a sample about double click on a JTable and it works fine. This sample defines a TableModel as shown at the end this note.
    On the other hand, I have an application in which I have defined a JTable
    using the DefaultTableModel as follows :
    DefaultTableModel dtm = new DefaultTableModel(data, names);
    JTable table  = new JTable(dtm);  where data and names are String arrays.
    Of course the mouse listener stuffs have been also specified.
    table.addMouseListener(new MouseAdapter(){
         public void mouseClicked(MouseEvent e){
          if (e.getClickCount() == 2){
             System.out.println(" double click" );
         } );Because the difference with the sample was the table model,
    I changed it with the DefaultTableModel class. At this point, the Double click does not work anymore.
    So I gues it should be an option which prevents double click to work.
    I thought of using mousePress() instead of mouseClick(), but it's very dangerous (I tried). . If by error the user clicks twice (instead of only once) the mousePress method is invoked twice for the same entry
    My question is now simple, may I use double click on a JTable with the default table model. If so, what I have to do ?
    Thanks a lot
    Gege
    TableModel dataModel = new AbstractTableModel() {
         public int getColumnCount() { return names.length; }
         public int getRowCount() { return data.length;}
         public Object getValueAt(int row, int col) {return data[row][col];}
         public String getColumnName(int column) {return names[column];}
         public Class getColumnClass(int col) {return getValueAt(0,col).getClass();}
         public void setValueAt(Object aValue, int row, int column) {
           data[row][column] = aValue;
         };

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class ClickIt extends MouseAdapter
        public void mousePressed(MouseEvent e)
            JTable table = (JTable)e.getSource();
            Point p = e.getPoint();
            if(e.getClickCount() == 2)
                System.out.println("table.isEditing = " + table.isEditing());
            int row = table.rowAtPoint(p);
            int col = table.columnAtPoint(p);
            String value = (String)table.getValueAt(row,col);
            System.out.println(value);
        private JTable getLeftTable()
            final String[] names = { "column 1", "column 2", "column 3", "column 4" };
            final Object[][] data = getData("left");
            TableModel dataModel = new AbstractTableModel() {
                public int getColumnCount() { return names.length; }
                public int getRowCount() { return data.length;}
                public Object getValueAt(int row, int col) {return data[row][col];}
                public String getColumnName(int column) {return names[column];}
                public Class getColumnClass(int col) {return getValueAt(0,col).getClass();}
                public void setValueAt(Object aValue, int row, int column) {
                    data[row][column] = aValue;
            JTable table = new JTable(dataModel);
            return configure(table);
        private JTable getRightTable()
            String[] colNames = { "column 1", "column 2", "column 3", "column 4" };
            JTable table = new JTable(new DefaultTableModel(getData("right"), colNames));
            return configure(table);
        private Object[][] getData(String s)
            int rows = 4, cols = 4;
            Object[][] data = new Object[rows][cols];
            for(int row = 0; row < rows; row++)
                for(int col = 0; col < cols; col++)
                    data[row][col] = s + " " + (row*cols + col + 1);
            return data;
        private JTable configure(JTable table)
            table.setColumnSelectionAllowed(true);
            table.setCellSelectionEnabled(true);
            table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            table.setPreferredScrollableViewportSize(table.getPreferredSize());
            table.addMouseListener(this);
            return table;
        private JPanel getContent()
            JPanel panel = new JPanel(new GridLayout(1,0,0,5));
            panel.add(new JScrollPane(getLeftTable()));
            panel.add(new JScrollPane(getRightTable()));
            return panel;
        public static void main(String[] args)
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setContentPane(new ClickIt().getContent());
            f.pack();
            f.setVisible(true);
    }

  • JTable select row by double click, single click

    Hi all,
    I would like to double click on the row of the JTable and pop up a window for adding stuff, a single click for selecting the row and then in the menu bar I can choose to etither add, change or delete stuff. I try to use the ListSelectionModel but does not seems to distinguish between double or single click.
    Any idea, doc, samples?
    or I should not use ListselectionModel at all?
    thanks
    andrew

    Hi. I used an inner class. By using MouseAdapter u dont have to implement all methods in the interface..
    MouseListener mouseListener = new MouseAdapter()
    public void mouseClicked(MouseEvent e)
    if(SwingUtilities.isLeftMouseButton(e))// if left mouse button
    if (e.getClickCount() == 2) // if doubleclick
    //do something
    U also need to add mouselistener to the table:
    table.addMouseListener(mouseListener);
    As I said, this is how I did it.. There are probably alot of ways to solve this, as usual :). Hope it helps

Maybe you are looking for

  • Different font colors in landscape not possible - SERIOUSLY??

    Hi Ive just been checking my portrait versions of a textbook and wow... there seems NO way to have different font colors in portrait and landscape?? Thats totally insane. I'll explain why... IN landscape you can (and should) have full bleed photos an

  • How do i install acrobat if my computer does not have dvd drive?

    I just purchased a untrabook. It does not have a dvd drive. How do i load/install acrobat (valid copy) w/out a dvd drive. Please, any suggestions??

  • Process Chain delays

    Process chain delay has default of 5 sec ,can that be reduced ?? is there any functional module,or program which can reduce this delays more?? thanks

  • Leopard swap file options

    hi, Back in Panther days you could force the swap file location but it got mucked up and frightfully complicated in Tiger. I have ram to spare. Can you force the OS to ether: A; never use a Swap file(I have 12 gb soon to be 16 GB EEC ram) or; B; use

  • Flash CS6(Mac)でステージに画像などを直接ドロップできない

    Flash CS6 MacBook Pro(Mountain Lion) で.表題のとおりFinder等からステージにドロップでアイテムを追加できません. ライブラリにはドロップすることができます. Lion環境でも試してみましたがダメでした. Windows版のCS6/CS5.5では可能で. MacでもCS5.5ではできた記憶があるのですが CS6で出来なくなってしまったのでしょうか? もし可能にする方法等ありましたら教えて頂けると幸いです.