A program of mine has a large number of JTextField elements. I'd like to provide a way to copy text from the text fields to the system clipboard. I found multiple methods of how to do this online (such as here), but they don't perform well with multiple fields, short of spamming duplicate code for each element, something that's hardly desirable for the large number of text fields.
So, is there a simple way to add the ability to copy and paste from multiple text fields in a Java Swing application?
I always make the same answer, but you can use Key Bindings
How to use KeyBindings
Suppose your textfields lives in the same container..
AbstractAction copyAction = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
for(Component c : container.getComponents()){
if(c instanceof JTextField){
//add copy paste action
}
}
}};
String key = "YOUR KEY COMBINATION HERE";
KeyStroke keyStroke = KeyStroke.getKeyStroke(key);
component.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
component.getActionMap().put(key, copyAction);