Mouse click in JTable

Hi All,
I want to force mouse click when right clicking on a JTable. I mean when the right click is done in the mouse, the left click should be forced. I have a JTable with some values in it. I want to select the particular column in the table when right click mouse action. How can I do it?
import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class TableDemo extends JFrame
    private JTable table;
    private JScrollPane jsp;
    private JPanel jp;
    public TableDemo()
        initComponents();
    private void initComponents()
        jp = new JPanel();
        String columnNames[] = { "Column 1", "Column 2", "Column 3" };
        String dataValues[][] =
            { "12", "234", "67" },
            { "-123", "43", "853" },
            { "93", "89.2", "109" },
            { "279", "9033", "3092" }
        table = new JTable(dataValues, columnNames);
        jsp = new JScrollPane(table);
        jsp.setViewportView(table);
        jp.add(jsp);
        table.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent evt) {
                if(evt.getButton() == 3) {
                    System.out.println("Right Click........");
                    // Mouse left click should be forced here to select the row.
                if(evt.getButton() == 1) {
                    System.out.println("Mouse LEFT CLICK FORCED.....");
        getContentPane().add(jp);
        pack();
        setVisible(true);
    public static void main(String args[])
        new TableDemo();
}

There may be a better way, but you could just use java.awt.Robot to perform the left click. I've changed your code around a bit: it shouldn't extend JFrame as it is in no way a special type of JFrame. And a GUI should always be launched on the EDT.**import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ForceLeftClick {
   private JTable table;
   private void makeUI() {
      String columnNames[] = {"Column 1", "Column 2", "Column 3"};
      String dataValues[][] = {
         {"12", "234", "67"},
         {"-123", "43", "853"},
         {"93", "89.2", "109"},
         {"279", "9033", "3092"}
      table = new JTable(dataValues, columnNames);
      JScrollPane scrollPane = new JScrollPane(table);
      scrollPane.setViewportView(table);
      table.addMouseListener(new MouseAdapter() {
         @Override
         public void mouseClicked(final MouseEvent evt) {
            if (evt.getButton() == MouseEvent.BUTTON3) {
               System.out.println("Right Click........");
               // Mouse left click should be forced here to select the row.
               //final Point point = evt.getLocationOnScreen();
               SwingUtilities.invokeLater(new Runnable() {
                  @Override
                  public void run() {
                     try {
                        Robot robot = new Robot();
                        //robot.mouseMove(point.x, point.y);
                        robot.mousePress(InputEvent.BUTTON1_MASK);
                        robot.mouseRelease(InputEvent.BUTTON1_MASK);
                     } catch (AWTException ex) {
                        ex.printStackTrace();
            if (evt.getButton() == MouseEvent.BUTTON1) {
               System.out.println("Mouse LEFT CLICK FORCED.....");
      JFrame frame = new JFrame();
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.add(scrollPane);
      frame.pack();
      frame.setVisible(true);
   public static void main(String args[]) {
      SwingUtilities.invokeLater(new Runnable() {
         @Override
         public void run() {
            new ForceLeftClick().makeUI();
}If there are issues of Robot clicking in the wrong location because the user moves the mouse before the robot does its stuff (not likely, but..), uncomment the two commented lines.
db
**edit And always use constant fields by name, not magic numbers. MouseEvent.BUTTON1, not 1. That keeps your code implementation independent.
Edited by: Darryl.Burke

Similar Messages

  • Emulating mouse click on JTable

    Hi. I'm trying to generate a mouse click on my table using:
    dispatchEvent(new MouseEvent(this, 0, System.currentTimeMillis(), 0, 0, 0, 1, false));
    but the program doesn't pick up the mouse event. What should I do?
    Thanks

    search www.globalleafs.com 's download section. there are some cool programmes out there.

  • Mouse Click on JTable

    Hello.
    I have a bunch of code that displays data in a Grid using Jtable. I need to capture the mouse double click event. But some how this simple code is just working on the Header of the grid but not working on the rows of that that Grid. Any clue? One more thing, the grid is editable as well.
    Thank you.
    Regards.
    Manish
    Edited by: 784024 on Jan 12, 2012 4:40 AM

    Thanks for reply,
    tableddMouseListener(new MouseAdapter() {
    public void mouseClicked(MouseEvent event) {
    if (e.getClickCount() == 2 && !e.isConsumed()) {
    e.consume();
    // handle double click here
    above code is working fine on non-editable row. But how can i do the same for editable row? the code that i have quit big enough to understand.
    i am planing
    a) on single click it start editing
    b) on double click it show a pop up message.
    any idea??
    Regards...
    Edited by: 784024 on Jan 13, 2012 5:54 AM

  • Detecting mouse clicks in editable cell of JTable

    Hi everyone :)
    I thought that this question might have been asked before, but I have searched the forums extensively and have not been able to find the solution.
    What I want to achieve is to detect single and double mouse clicks on JTable cells (that are editable).
    For example, I have a JTable and there exists within it an editable cell. If the user clicks on it once then that cell goes into edit mode, and the user can type directly into the cell. I have already successfully implemented this.
    However, what I also want to do is detect a double-click so that I can pop up a dilaog that shows a list of default values that the user can select.
    So here is what I want;
    1. User clicks on the cell once.
    2. Cell moves into edit mode.
    3. If the user clicks again within a certain time interval then cancel edit mode and pop up a dialog containing values that the user can select from.
    I think that to do this I need to be able to detect mouse clicks on the cell that is currently being edited. So far I have been unable to discover how this is done. I have even tried extending JTextField to get what I want, but with no luck.
    Any help would be greatly appreciated.
    Kind regards,
    Ben Deany

    Thanks for the reply.
    Unfortunately, it is not possible to call 'AddMouseListener()' on a cell editor. You are only able to call 'addCellEditorListener()' and that only allows two events to the broadcast (edit cancel, and edit stop).
    Ben

  • Multiple JButtons inside JTable cell - Dispatch mouse clicks

    Hi.
    I know this subject has already some discussions on the forum, but I can't seem to find anything that solves my problem.
    In my application, every JTable cell is a JPanel, that using a GridLayout, places vertically several JPanel's witch using an Overlay layout contains a JLabel and a JButton.
    As you can see, its a fairly complex cell...
    Unfortunately, because I use several JButtons in several locations inside a JTable cell, sometimes I can't get the mouse clicks to make through.
    This is my Table custom renderer:
    public class TimeTableRenderer implements TableCellRenderer {
         Border unselectedBorder = null;
         Border selectedBorder = null;
         public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                   boolean hasFocus, int row, int column) {
              if (value instanceof BlocoGrid) {
                   if (isSelected) {
                        if (selectedBorder == null)
                             selectedBorder = BorderFactory.createMatteBorder(2,2,2,2, table.getSelectionBackground());
                        ((BlocoGrid) value).setBorder(selectedBorder);
                   } else {
                        if (unselectedBorder == null)
                             unselectedBorder = BorderFactory.createMatteBorder(2,2,2,2, table.getBackground());
                        ((BlocoGrid) value).setBorder(unselectedBorder);
              return (Component) value;
    }and this is my custom editor (so clicks can get passed on):
    public class TimeTableEditor extends AbstractCellEditor implements TableCellEditor {
         private TimeTableRenderer render = null;
         public TimeTableEditor() {
              render = new TimeTableRenderer();
        public Component getTableCellEditorComponent(JTable table, Object value,
                boolean isSelected, int row, int column) {
             if (value instanceof BlocoGrid) {
                  if (((BlocoGrid) value).barras.size() > 0) {
                       return render.getTableCellRendererComponent(table, value, isSelected, true, row, column);
             return null;
        public Object getCellEditorValue() {
            return null;
    }As you can see, both the renderer and editor return the same component that cames from the JTable model (all table values (components) only get instantiated once, so the same component is passed on to the renderer and editor).
    Is this the most correct way to get clicks to the cell component?
    Please check the screenshot below to see how the JButtons get placed inside the cell:
    http://img141.imageshack.us/my.php?image=calendarxo9.jpg
    If you need more info, please say so.
    Thanks.

    My mistake... It worked fine. The cell span code was malfunctioning. Thanks anyway.

  • Multiple Buttons in JTable Headers:  Listening for Mouse Clicks

    I am writing a table which has table headers that contain multiple buttons. For the header cells, I am using a custom cell renderer which extends JPanel. A JLabel and JButtons are added to the JPanel.
    Unfortunately, the buttons do not do anything. (Clicking in the area of a button doesn't appear to have any effect; the button doesn't appear to be pressed.)
    Looking through the archives, I read a suggestion that the way to solve this problem is to listen for mouse clicks on the table header and then determine whether the mouse clicks fall in the area of the button. However, I cannot seem to get coordinates for the button that match the coordinates I see for mouse clicks.
    The coordinates for mouse clicks seem to be relative to the top left corner of the table header (which would match the specification for mouse listeners). I haven't figured out how to get corresponding coordinates for the button. The coordinates returned by JButton.getBounds() seem to be relative to the top left corner of the panel. I hoped I could just add those to the coordinates for the panel to get coordinates relative to the table header, but JPanel.getBounds() gives me negative numbers for x and y (?!?). JPanel.getLocation() gives me the same negative numbers. When I tried JPanel.getLocationOnScreen(), I get an IllegalComponentStateException:
    Exception in thread "AWT-EventQueue-0" java.awt.IllegalComponentStateException: component must be showing on the screen to determine its location
    Can someone tell me how to get coordinates for the button on the JTableHeader? Or is there an easier way to do this (some way to make the buttons actually work so I can just use an ActionListener like I normally would)?
    Here is relevant code:
    public class MyTableHeaderRenderer extends JPanel implements TableCellRenderer {
    public MyTableHeaderRenderer() {
      setOpaque(true);
      // ... set colors...
      setBorder(UIManager.getBorder("TableHeader.cellBorder"));
      setLayout(new FlowLayout(FlowLayout.LEADING));
      setAlignmentY(Component.CENTER_ALIGNMENT);
    public Component getTableCellRendererComponent(JTable table,
                                                     Object value,
                                                     boolean isSelected,
                                                     boolean hasFocus,
                                                     int row,
                                                     int column){
      if (table != null){
        removeAll();
        String valueString = (value == null) ? "" : value.toString();
        add(new JLabel(valueString));
        Insets zeroInsets = new Insets(0, 0, 0, 0);
        final JButton sortAscendingButton = new JButton("1");
        sortAscendingButton.setMargin(zeroInsets);
        table.getTableHeader().addMouseListener(new MouseAdapter(){
          public void mouseClicked(MouseEvent e) {
            Rectangle buttonBounds = sortAscendingButton.getBounds();
            Rectangle panelBounds = MyTableHeaderRenderer.this.getBounds();
            System.out.println(Revising based on (" + panelBounds.x + ", "
                               + panelBounds.y + ")...");
            buttonBounds.translate(panelBounds.x, panelBounds.y);
            if (buttonBounds.contains(e.getX(), e.getY())){  // The click was on this button.
              System.out.println("Calling sortAscending...");
              ((MyTableModel) table.getModel()).sortAscending(column);
            else{
              System.out.println("(" + e.getX() + ", " + e.getY() + ") is not within "
                                 + sortAscendingButton.getBounds() + " [ revised to " + buttonBounds + "].");
        sortAscendingButton.setEnabled(true);
        add(sortAscendingButton);
        JButton button2 = new JButton("2");
        button2.setMargin(zeroInsets);
        add(button2);
        //etc
      return this;
    }

    I found a solution to this: It's the getHeaderRect method in class JTableHeader.
    table.getTableHeader().addMouseListener(new MouseAdapter(){
      public void mouseClicked(MouseEvent e) {
        Rectangle panelBounds = table.getTableHeader().getHeaderRect(column);
        Rectangle buttonBounds = sortAscendingButton.getBounds();
        buttonBounds.translate(panelBounds.x, panelBounds.y);
        if (buttonBounds.contains(e.getX(), e.getY()) && processedEvents.add(e)){  // The click was on this button.
          ((MyTableModel) table.getModel()).sortAscending(column);
    });

  • How to Select  a Row in a JTable, on a right mouse click?

    Hi all!
    I need to know the Row index in a JTable, on a right mouse click?
    Executing following code, I get the "Column Number" on a mouse click
    TableColumnModel columnModel = tableView.getColumnModel();
    int viewColumn = columnModel.getColumnIndexAtX(e.getX());
    int columnIdx = tableView.convertColumnIndexToModel(viewColumn);
    Dows any body know the code that gets "rowIdx" on a mouse e.getY() method??
    Hope early response!

    int row = table.rowAtPoint( e.getPoint() );
    int column = table.columnAtPoint( e.getPoint() );

  • How to select a row in JTable for right mouse click ?

    Hi All,
    I need to select a row on JTable for right mouse click ?
    Can any one help me ?
    Thanks a lot.
    Seelam.

    Got solution...
    tabel.addRowSelectionInterval(..) works.
    thanks.

  • Changing mouse click behavior on JTable

    Hi everybody,
    The default behavior of a mouse click on a jTable is selection of the cell.
    I would like to change the behavior so when the user clicks once on the cell, the content can be marked and is ready to change. That would give the user the same feeling as Excel.
    Is there any way that I can do this without writing a new mouse/event handler?
    thanks,

    With a call to getSelectionModel() of JTable, you can get a reference to the ListeSelectionModel.
    This is in fact an instance of DefaultListSelectionModel, which allows you to set a new listener object using addListSelectionListener(ListSelectionListener l).
    All you have to do then is implement a custom ListSelectionListener which handles events as you want.
    Unfortunately there isnt going to be a way of avoiding writing a Listener, but this is how you would go about it.
    colr__

  • Mouse clicks count!

    Hello!
    I have a JTable. I added a mouse listener to it! The problem is that I cannot count the mouse clicks correctly!
    I have:
    mouseClicked(... e){
    e.getClickCount()
    but I only get 1 click, despite the double click I made!
    Does the table mouse listener erases the preceding event and never gets to count the second click? I got the behaviour of two single clicks!
    THANKS in advance!
    Rui Vale

    ... the the milli between the events... if they are say 40 milli or less the action is a double click...if not restart the chronometer...You can use other listener to...it depends on what you want to do!
    JRG

  • Simulate a mouse click

    Anyone knows how to simulate a mouse click?
    I mean, for exmaple, when a user clicks a button another button is pressed too, with the click of the first button (without a click on itself).

    Let me explain my problem:
    I want to sort two JTables in simultaneus, they have the same header and the same columns but they have different data and differents models. I don't know how to sort the two tables data when the user clicks on some column of any table. The tables contain data of a first team and a second team of a soccer club. The unique solution that i've imagin is to simulate a mouse click in the column of the second table if the user clicks on the first and vice versa.

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

  • I am using FireFox 4. Where is the "Bookmark All Tabs-" feature. I would like to save my Tabs for a later session. The selection is not on the menu when I right-mouse click or go to the Bookmarks feature of the Menu.

    Missing "Bookmark All Tabs…" feature which was in previous versions of FireFox 3.x. If you right-mouse click on a neutral part of the Browser window, there would be choice of "Bookmark this page" or "Bookmark All Tabs…". I have been unable to find it either in the sub-menu or the BOOKMARK selection from the Menu Bar.

    What do you mean by Tabs sub-menu is it right-clicking on a tab ?
    I know that "ctrl-shift-D" still work.
    I know that a right-click on a tab gives the "Bookmark all Tabs" function.
    But I would like to see it back in the Bookmarks menu. (which is its logical place)
    Because today the choice only disappeared from the menu as it is still reachable through keyboard shortcut or through mouse right-click on a tab
    but tomorrow it will totally disappear and personally I don't want that as this is one of my favorite functionality.
    Tank you for your understanding !

  • How do I set my project to advance to next slide on mouse click vs just play?

    Captivate 6 on mac running OS 10.7.5 file format in question .htm (firefox)
    I'm brand new to Captivate 6 (never used it before) I have put together a mock presentation from scratch which has a few introductory slides then a quiz. When I publish it there is a "play" button which is NOT the behavior I want.
    I watched a training video from Lynda.com and the insstructor imported a PPT file, there was a dialog box which asked the how to advance slide, there was a drop down menu and one of two options was advance "on mouse click". This is the behavior I'm looking for.
    I've scoured the internet and forums etc to find a comparable option elsewhere in Captivate 6 when creating from scratch vs importing from PPT and cannot find one anywhere. I've also read that you can insert a click box object and that that would do what I'm looking for but that doesn't work either.
    Does any such option exist and if so where/ how do I get to it/ use it. Please see attachments below. First screen shot is the first slide I get which isn't the first slide either, what's up with that? Next one is simply to show how the project just "plays" instead of advancing slide by slide. Third is my publish dialog box. Bottom line I don't want a "play" button I want the user to mouse click next, next, next etc. How do I do this?
    Thank you for any help or suggestions!

    Maybe I understand something wrongly, but thought you also wanted to know how you can make slides advance on clicking the Next button instead of having it playing on automatically? And instead of using the playbar you want to have a Previous and Next button?
    The way imported PPT with advance on Mouse click works is because there is a click box added to each slide that pauses that slide at its end. The user has to click on the slide to advance.
    A click box is an 'interactive' object: this means that you can have it pausing the slide, that the user can interact with it and trigger an action like 'Go to Next Slide'.
    You added (from what I see on the last screenshot) another interactive object, but now I'm confused: the third screenshot has a Prev and Next arrow, I think those are shapes. You do not need to add a click box on top of them (what I see on the last screenshot), they can be converted themselves into buttons. I blogged a lot about those shape buttons. Anyway, both click box and shape button can pause the slide. This is the case by default for click boxes (at the end of their duration, their timeline), for shape buttons you have to tell them to pause in the Timing accordion. In your case I certainly would choose a shape button because they can be put on a master slide, or timed for the rest of the project whereas Click boxes need to be unique on each slide, you'l have a lot of copy/paste to do then. In the Action accordion, On Success you choose the action, I think in this case you want 'Go to Next Slide' for the Next 'thing'
    As for the first screenshot, Rod explained that you cannot get rid of the play button for pdf output, but you can have a poster image instead of the blank screen. There is a folder icon in Preferences, Project, Start and End when you deselect AuotPlay.
    Here is a link to an article where I explain shape buttons:
    http://lilybiri.posterous.com/why-i-like-shape-buttons-captivate-6
    There is an on-demand webinar as well on the Adobe site which I presented, only about shape buttons.
    Lilybiri

  • How can i open a link in new window (shift + Mouse Click) while not switching to the new window

    I want to open a new window (shift + Mouse Click) while not switching to the newly opened window. The focus should remain on the window from where i have opened the link.

    You can do that with tabs, but not with windows AFAIK.

Maybe you are looking for

  • Question about I/O

    How can i combine a mac of ' HmacMD5' and a random integer as a object and then send it through a Server socket ? Then in a client side i how can receive and separate them them? I hope someone can help me. Thanks !

  • Import legacy photos into Aperture 3 from iPhoto?

    By way of background I have a 20" iMac bought January 2007 which I soon plan to replace with a new 27" iMac. I expect to purchase Aperture 3 with the new iMac and to commence using it to edit my photographic images. With my  present iMac I use iPhoto

  • Anyone else seeing a double arrow?

    Hi all- Frequently when I am using LR4, from the intial to the latest patch, I have a very persistent double arrow. The double arrow is the one that points left and right, and is intended to occur when you are hovering over the side of a window pane

  • ClassCastExceptions in Java6 leak memory (not heap, but VM memory)

    I have been closely monitoring this reported bug for a while ( [6676058|http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6676058] ), and still cannot get any answers. It was marked as Closed, duplicate of [6631248|http://bugs.sun.com/bugdatabase/vi

  • OLAP Query not running

    Hi Gurus I am getting and exception while executing a MDX Query through OLAP Query . All my queries were running properly until yesterday from OLAP query as well as through MDXTest TCode . But today it gives me an excetion com.sap.lhcommon.webservice