How do I click a JButton in a Swing app so that some text in a TextField can be copied (instead of highlight the text and press ctrl+C), then in a Wordpad I can click the paste button in it to paste the copied text from the Java app ?
+1
A:
You need to put the text on the clipboard. This article talks about that so it might be what you are looking for.
Vincent Ramdhanie
2009-11-30 04:31:19
A:
Well usually that is done by adding menu items to your application.
Check out the section from the Swing tutorial on Text Component Features for a working example that shows one way to do this.
Another way is to use the DefaultEditorKit.CopyAction. You create the Action, then you can add it to a menu item or JButton or any component that accepts an Action.
Action copy = new DefaultEditorKit.CopyAction();
JButton button = new JButton( copy );
Of course the user will still have to select the text they want copied (but your question did say "some text").
Or is you question about how to select all the text automatically?
camickr
2009-11-30 04:34:14
Yes, how to get the text automatically into a clip board ?
Frank
2009-11-30 20:02:18
+1
A:
try this:
copyBtn = new JButton(new AbstractAction("copy"){
public void actionPerformed(ActionEvent e){
Clipboard system = Toolkit.getDefaultToolkit().getSystemClipboard();
StringSelection sel = new StringSelection(myTextField.getText());
system.setContents(sel, sel);
}
});
pstanton
2009-11-30 04:35:04
This works the best, I just need to include the following two lines :import java.awt.datatransfer.Clipboard;import java.awt.datatransfer.StringSelection;
Frank
2009-11-30 20:11:01