-
Notifications
You must be signed in to change notification settings - Fork 79
Expand file tree
/
Copy pathTextTransferFrame.java
More file actions
84 lines (76 loc) · 2.19 KB
/
Copy pathTextTransferFrame.java
File metadata and controls
84 lines (76 loc) · 2.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package transferText;
import java.awt.*;
import java.awt.datatransfer.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
/**
* This frame has a text area and buttons for copying and pasting text.
*/
public class TextTransferFrame extends JFrame
{
private JTextArea textArea;
private static final int TEXT_ROWS = 20;
private static final int TEXT_COLUMNS = 60;
public TextTransferFrame()
{
textArea = new JTextArea(TEXT_ROWS, TEXT_COLUMNS);
add(new JScrollPane(textArea), BorderLayout.CENTER);
JPanel panel = new JPanel();
JButton copyButton = new JButton("Copy");
panel.add(copyButton);
copyButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
copy();
}
});
JButton pasteButton = new JButton("Paste");
panel.add(pasteButton);
pasteButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
paste();
}
});
add(panel, BorderLayout.SOUTH);
pack();
}
/**
* Copies the selected text to the system clipboard.
*/
private void copy()
{
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
String text = textArea.getSelectedText();
if (text == null) text = textArea.getText();
StringSelection selection = new StringSelection(text);
clipboard.setContents(selection, null);
}
/**
* Pastes the text from the system clipboard into the text area.
*/
private void paste()
{
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
DataFlavor flavor = DataFlavor.stringFlavor;
if (clipboard.isDataFlavorAvailable(flavor))
{
try
{
String text = (String) clipboard.getData(flavor);
textArea.replaceSelection(text);
}
catch (UnsupportedFlavorException e)
{
JOptionPane.showMessageDialog(this, e);
}
catch (IOException e)
{
JOptionPane.showMessageDialog(this, e);
}
}
}
}