Reaction on a double click in a JTable

Hello guys,
I need to react on a double click on some row in a JTable. I know it must be simple, but I can't find a way to do it!
Any help will be appreciated.

Here is a code snipplet out of an application of mine.
The purpose is to do the same action on double click that would be done by pushing the OK button.
        // Take selected order item on double click.
        this.table.addMouseListener(new MouseAdapter() {
            public void mouseClicked(final MouseEvent e) {
                if (e.getClickCount() == 2) {
                    Point origin = e.getPoint();
                    int row = OrderSearchDlg.this.table.rowAtPoint(origin);
                    if (row > -1) {

Similar Messages

  • 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
    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);
        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)
            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.setContentPane(new ClickIt().getContent());

  • How to start a function when double-clicked in a JTable

    hi there,
    i got a problem, i want that my JTable reacts when i make a double-click on any row... so that i can start a method that does the things i want to...
    how can i realize that?
    thx anyway

    i got a problem, i want that my JTable reacts when i
    make a double-click on any row... so that i can start
    a method that does the things i want to...
    how can i realize that?Easy, just put a mouse listener on it the same way you would a button! In the listener method, you can use
    if ( event.getClickCount()>1 ){

  • Double click in a JTable row

    I have the following problem. I would like to have a JTable with single selection (this is ok so far), but I would like it to have the following behaviour.
    If a row is clicked, it becomes selected. If a selected row is clicked again it becomes deselected.
    Does anyone have any suggestions?

    I am writing about JTree rather than JTable ... because there are no other replies I figured it's better than nothing ...
    This code does the behavior you describe to a JTree.
    (Code snippet copied from JTree javadoc page and modified by me.)
    java.awt.event.MouseListener ml = new java.awt.event.MouseAdapter() {
    public void mouseClicked(java.awt.event.MouseEvent e) {
    int selRow = tree.getRowForLocation(e.getX(), e.getY());
    if(selRow != -1) {
    if(e.getClickCount() == 1) {
    System.out.println("SINGLE CLICK");
    else if(e.getClickCount() == 2) {
    System.out.println("DOUBLE CLICK");
    I put the print statements in to demonstrate that a double-click event actually is a single-click followed by a double-click. Since you didn't sound like you need to do any custom code for the single-click case, this fact probably doesn't affect you.
    I hope I helped

  • Previous entered value is lost when double click in the Jtable cell.

    When I double click the cell in the Jtable, the pervious enter data is lost. I unable to mask the double click event also. Could you please help me out.
    Thanks in Advance,
    With Thanks and Regards,

    When I double click the cell in the Jtable, the pervious enter data is lost.No it isn't unless you've customized the code and made an error.
    If you need further help then you need to create a [Short, Self Contained, Compilable and Executable, Example Program (SSCCE)|], that demonstrates the incorrect behaviour.
    Don't forget to use the Code Formatting Tags so the posted code retains its original formatting. That is done by selecting the code and then clicking on the "Code" button above the question input area.

  • Double click event for JTable.....

    I would like to display some data on double_click a selected row from the JTable. How do I code the double_click event in the following program. Please advise.
    Here is the code:
    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);
    //Add the scroll pane to this window.
    getContentPane().add(scrollPane, BorderLayout.CENTER);
    getContentPane().add(button = new JButton("Add Row"),
    getContentPane().add(buttonQuery = new JButton("Query"), BorderLayout.NORTH);
    button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    Object [] aRow = new Object [8];
    for (int i=0; i<5; i++) {
    aRow = new Integer(count+i);
    count += 10;
    buttonQuery.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    System.out.println(myModel.getValueAt(1, 3));
    addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    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) {
    fireTableRowsInserted(data.size()-1, data.size()-1);
    public static void main(String[] args) {
    TableTest frame = new TableTest();

    Thanks, but I get 1 error:
    'Cannot resolve symbol' -class MouseInputAdapter
        import java.awt.event.MouseAdapter;
    Also say if I need to get 'column data' from selected
    row, what will be the command like ?
        int col = table.columnAtPoint(p);>
    Best Regards

  • Resize JTable columns by double-clicking header

    I want to implement column resizing in a JTable so that when the user double clicks on the column header with the mouse in the "resize zone" the column automatically adjusts to the width of the longest text in the column. this is how many applications behave (e.g. windows explorer) but I don't think I've ever seen a swing app that does this. I've looked in the API docs for JTable and JTableHeader and I can't see any way of finding out if the mouse is over the edge of a column header. does anyone know of a way to do this?

    Is this laf independant?import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class Test extends JFrame {
      public Test() {
        Container content = getContentPane();
        String[] head = {"One","Two","Three"};
        String[][] data = {{"R1-C1","R1-C2","R1-C3"},
        JTable jt = new JTable(data, head);
        JScrollPane jsp = new JScrollPane(jt);
        content.add(jsp, BorderLayout.CENTER);
        JTableHeader jth = jt.getTableHeader();
        jth.addMouseListener(new MouseAdapter() {
          public void mouseClicked(MouseEvent me) {
            JTableHeader jth = (JTableHeader)me.getSource();
            int col = jth.columnAtPoint(me.getPoint());
            Rectangle r = jth.getHeaderRect(col);
            if (jth.getCursor().equals(Cursor.getPredefinedCursor(Cursor.E_RESIZE_CURSOR))) {
              System.out.println("Cursor, col="+col);
        setSize(300, 300);
      public static void main(String args[]) { new Test(); }

  • JComboBox in JTable to activate when double-click instead of single-click

    I like to know if it is possible to change the default behaviour of JComboBox within the JTable,
    such that instead of single click on the JTable cell for the combo box's popup to appear, I double click on it instead.
    If it is possible please give some advice.

    I couldn't get to settings because I couldn't scroll and don't know where that is located. I just saw a similar question from someone else. Three clicks on home button worked to turn off voiceover !! Phew!

  • 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?

    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:
    As I said, this is how I did it.. There are probably alot of ways to solve this, as usual :). Hope it helps

  • JTable - detecting double click

    i'm trying to detect double click on a row in a JTable and then find out the row number. i can get it to detect the double click with the table disabled but the row always comes back as -1. if i try setEnabled(false) it doesn't detect the double click at all.

    I think your table should be enabled. Put a mouse listener on the table like:
    myJTable.addMouseListener(new ClickMouseListener());
    class ClickMouseListener extends MouseAdapter
        public void mouseClicked(MouseEvent e)
          if (e.getClickCount() == 2)
            Point pt = e.getPoint();
            int row = myJTable.rowAtPoint(pt);
            System.out.println("Mouse clicked on row " + row);
    }If you also have selection enabled then the row will also be the selected one so that would be another way of determiing the row number.

  • JTable: double clicking triggers some action

    Hi there,
    A double click on a row of a JTable makes usually the underlying cell editable. This is the default behaviour of a JTable.
    In my application, the JTable only shows data, without giving users editing rights. Beside that, I'd like that a double click on a row, triggers other actions, like for example copying the selected row to the clipboard or sending it per mail....
    How do I have to configure the JTable for these purposes? Do I have to override the default ListSelectionListener? Did anybody make experiences with that?
    Thanks for your help,
    Best regards,

    like for example copying the selected row to the clipboardCtrl-C is the default KeyStroke combination for this.
    Beside that, I'd like that a double click on a row, triggers other actions...Then you need to add a MouseListener to the table. Then use:
    columnAtPoint(...);to determine which cell was clicked

  • Listen double clicks on JTable's row

    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, 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..

    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.
    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) {
                        int[] selected_rows = table.getSelectedRows();
                            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..

  • 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:
    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 ){
    e.getX(), e.getY() );
    But when double clicking, nothing happens.
    Anyone have any idea to implement this or over-ride an editable cell?

    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() );
                             source.changeSelection(row, column, false, false);
              getContentPane().add( new JScrollPane(table) );
         public static void main(String[] args)
              TableRightClick frame = new TableRightClick();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.setLocationRelativeTo( null );
              frame.setVisible( true );

  • JTable & mouse double-click?

    When I double-clicked a row in a JTable ,how can i get one column's value in that can i do with the mouse event.
    some examples are preferred.
    thankx in advance !

    When you say "one column's value in that row" do you mean that you want the value that the user double-clicked?
    When you receive a mouse event, get the selected rows and columns from the table, then get the value from the table model using the getValueAt() method.
    int[] selectedRows = table.getSelectedRows();
    int[] selectedCols = table.getSelectedColumns();
    String selectedElement = (String)model.getValueAt(selectedRows[0], selectedCols[0]);
    System.out.println(selectedElement + " selected");

  • JTable's cell double click question...

    Hello everyone,
    My JTable has some cells with icons and text, and some contains only text.
    All cells are editable, so double clicking on it goes to "edit mode" where user enters new value for the cell.
    Here is my question: Can I somehow determine if user has clicked on an icon?
    What I'm trying to do is to put additional information for cell (some comment), and if comment exists, icon will appear.
    Double clicking on that icon, dialog will show that comment.
    Thanks in advance!

    You did not mention that before. ...You are absolutely right, I didn't.
    Let me emphasize importance of this:
    Can I somehow determine if user has clicked on an icon?
    And when I said "clicked" I mean double click when entering edit mode
    of a cell.
    If I could somehow determine that, I could than
    perform desired action (open a dialog, or something else).
    Thank you for your help so far.

Maybe you are looking for

  • Transfer from XP to 10.4

    Hi, Sorry i'm not sure where to post this question. I'm looking to move all music in itunes on a winbook with XP on it. I tried connecting a ethernet cable but the mac doesn't seem to recognize the laptop. I have a wireless card on the winbook but do

  • IMac SuperDrive stopped working with Mountain Lion 10.8.2

    HELP! My IMac was patched last yesterday and the SuperDrive has stopped working. The drive is empty but I cannot insert a CD into it. Should I have to await another patch from Apple? Can someone recommend another solution I can use today? Support fol

  • Old key field FROMNUMBER is now non-key field

    Hi All, I am getting one issue with NRIV table.When I tried to activate this table from se11 it is giving error as   Program start============================================================   Mass activation   =======================================

  • HT1218 What fix works for 'the backup disk image X could not be accessed (error-1)?

    Our backup fails every time and leaves the message: The backup disk image "X" could not be accessed (error -1). The Mac Help options all look like solutions to other problems. How do you fix this?

  • Should be a simple question...

    Hi, When searching in Mac how what are wildcards? For instance I'm using the search tool to search for all files that are greater than 100Mb. I've clicked the plus button and put the file size criteria in, however I can't make it search for all files