java/swing: clipboard paste

2020-02-15 04:41发布

问题:

I have a DropTargetListener setup to allow me to drag + drop strings into some tables of my Swing application -- on a drop, I parse the string and insert data into the table.

I would like to do the same thing with a clipboard paste (Ctrl-V). What literature is there to explain how to handle clipboard pastes? I'm looking at some stuff from Sun's website and it seems bizarre, like this should be simpler.

回答1:

This answer by Bozhidar Batsov is the best solution I have seen around, simple and extensible. After adding his class file, this is how I implemented his class

txtTextField.addMouseListener(new ContextMenuMouseListener());

Adding additional actions should be pretty simple:

  1. add a new Action class field,
  2. Add the action to the enum Actions
  3. Add an AbstractAction with the desired functions
  4. Add the new action to the popup
  5. Add the needed logic to the mouseClicked(MouseEvent e) method

And there you go. I added the detail here partly to make sure I understand it, and also to give those after me a clear understanding of what needs to be done. Don't forget to include the necessary imports!



回答2:

As shown in the intro and the ListCutPaste demo, the two are connected. The DnD gets you CCP automatically.



回答3:

I would instead suggest you to take a look at java.awt.datatransfer.Clipboard class documentation. I think it will go along with your DnD operations.