2

I'm trying to enable ctrl c on the actual cell of the Jtable, instead of the whole row. I know how to disable the ctrl c on the whole row.

KeyStroke cStroke = KeyStroke.getKeyStroke(KeyEvent.VK_C, InputEvent.CTRL_MASK);
inputMap.put(cStroke,  "none");

I have tried the following to add a ctrl c to the cell itself: adding a keylistener to the table itself. It did not work. And the following code:

Action actionListener = new AbstractAction() {
    public void actionPerformed(ActionEvent actionEvent) {
        System.out.println("activated");
    }
};
KeyStroke cStroke = KeyStroke.getKeyStroke(KeyEvent.VK_C, InputEvent.CTRL_MASK);
inputMap.put(cStroke,  actionListener);

It did not print activated.

I have read JTable: override CTRL+C behaviour but it does not contain an answer, at least not a specific answer..

Beast Julian
  • 63
  • 10
  • You don't need to add an action listener to a cell... you should be listening for events from the "cut" menu item as well as the CTRL+C key combo and then running your own code for however you want the copy operation to proceed. Are you pretty new to the concept of implementing CCP? It seems like some of your assumptions on how things work is a bit shaky. – MarsAtomic Jan 12 '19 at 02:25
  • Copy content to the clipboard is relatively easy. Binding the key action to the table is relatively easy. The difficulty is actually in the exporting of the data in a usable format. How you do that will depend on your underlying data and your intended use of it – MadProgrammer Jan 12 '19 at 07:42
  • I'd also recommend look at [Copy jTable row with its grid lines into excel/word documents](https://stackoverflow.com/questions/24966974/copy-jtable-row-with-its-grid-lines-into-excel-word-documents/24978019#24978019) and [JTable copy and paste using Clipboard and AbstractAction](https://stackoverflow.com/questions/22622973/jtable-copy-and-paste-using-clipboard-and-abstractaction/22623240#22623240) for some more ideas – MadProgrammer Jan 12 '19 at 07:44
  • @MadProgrammer could you by any chance remove the duplicate, it is significantly different and makes absolutely no sense to mark it as a duplicate. I've also gone through all these questions.. – Beast Julian Jan 12 '19 at 10:48
  • @MarsAtomic new to java swing, have worked with javafx for some years. I wasn't trying to add an action listener to a cell haha, read again :) I see the confusion tho ".. to the cell itself: adding a keylistener to the table itself" I meant to the table obviously (2nd part of the sentence), but it took the value of the cell :D So I was trying to add the actionlistener with table getCell to the table :) – Beast Julian Jan 12 '19 at 10:52
  • This question was originally closed as a duplicate of: https://stackoverflow.com/questions/22583589/jtable-right-click-copy-paste-menu-to-copy-cell-data-on-one-click. The OP doesn't think it is a duplicate and I tend to agree (so I reopened the question). This question is about using key bindings to invoke a custom Action. The other question is about using a popup menu. Although the code for the Action is the same in both cases, the issue with this question is using key bindings correctly. – camickr Jan 12 '19 at 15:44
  • @BeastJulian, check out [Using Key Bindings](https://tips4java.wordpress.com/2008/10/10/key-bindings/) for more examples of playing with the InputMap and ActionMap to handle Key Bindings. – camickr Jan 12 '19 at 15:48
  • @camickr I think that I understand it pretty well now. The main problem was that I had no idea what to place as the string value (so "copy" for example) in the inputmap. Now only left with the question how to change that when i type in the cell i start a new textvalue instead of adding it to the existing value in the textfield. So when the cellvalue is "hello" and i type "world" it should only say world, instead of "helloworld" – Beast Julian Jan 12 '19 at 16:02
  • `I had no idea what to place as the string value (so "copy" for example)` - the link I provided also shows how to do that. `Now only left with the question how to change that when i type in the cell i start a new textvalue instead of adding it to the existing value in the textfield` - well that is a completely different topic for another question. – camickr Jan 12 '19 at 20:52

1 Answers1

5

You can copy selected cell's content to the clipboard like this:

import javax.swing.*;
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionEvent;

public class CopyCell
{
  public static void main(String[] args)
  {
    JTable table = new JTable(
        new String[][] {{"R1C1", "R1C2"}, {"R2C1", "R2C2"}},
        new String[] {"Column 1", "Column 2"});

    table.getActionMap().put("copy", new AbstractAction()
    {
      @Override
      public void actionPerformed(ActionEvent e)
      {
        String cellValue = table.getModel().getValueAt(table.getSelectedRow(), table.getSelectedColumn()).toString();
        StringSelection stringSelection = new StringSelection(cellValue);
        Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection, stringSelection);
      }
    });

    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.getContentPane().add(new JScrollPane(table));
    f.setBounds(300, 200, 400, 300);
    f.setVisible(true);
  }
}
Prasad Karunagoda
  • 2,048
  • 2
  • 12
  • 16
  • Gonna try it. Where can I find the valid paramters for the actionmap. Such as "copy", how could I know that is a valid argument? – Beast Julian Jan 12 '19 at 10:45
  • 1
    You can print all the keys in the ActionMap like this: `Arrays.stream(table.getActionMap().allKeys()).forEach(System.out::println);` – Prasad Karunagoda Jan 12 '19 at 11:08
  • Thanks man! appreciate it. What about ctrl v on the cell instead of first having to go into the actual textfield? – Beast Julian Jan 12 '19 at 11:29
  • 1
    Similarly I set a custom `Action` for "paste" in the ActionMap and it worked. Unfortunately I cannot add the full code here bcoz of the character limit in these comments. But it mainly has these 3 lines inside actionPerformed: `Transferable transferable = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);` `Object data = transferable.getTransferData(transferable.getTransferDataFlavors()[0]);` `table.getModel().setValueAt(data, table.getSelectedRow(), table.getSelectedColumn());` – Prasad Karunagoda Jan 12 '19 at 12:15
  • Thank you very much, I've done it way different hehe since I already made copy/paste/cut actions for my right click menu. I basically just added that and now it's working in synergy :D I just didn't get the inputmap i guess. Thanks a whole lot ! – Beast Julian Jan 12 '19 at 13:08
  • o.. If i type text in the cell now it's adding what im typing to the textfield in the cell, instead of starting a new textvalue – Beast Julian Jan 12 '19 at 14:10