Frank
Frank

Reputation: 31096

How to copy text from Java app to wordpad

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 ?

Upvotes: 0

Views: 1479

Answers (3)

pstanton
pstanton

Reputation: 36640

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);
    }    
});

Upvotes: 2

camickr
camickr

Reputation: 324128

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?

Upvotes: 1

Vincent Ramdhanie
Vincent Ramdhanie

Reputation: 103135

You need to put the text on the clipboard. This article talks about that so it might be what you are looking for.

Upvotes: 1

Related Questions