自己利用ClipBoard搞了一个小东西,献丑了!
import java.awt.BorderLayout;import java.awt.Dimension;
import java.awt.ScrollPane;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JToolBar;
public class ClipBoard implements ActionListener, ClipboardOwner {
private JFrame jf;
private JButton jbcopy, jbpaste, jbcut;
private JToolBar jt;
private JTextArea jta;
private Clipboard clip;
private ScrollPane sp;
public ClipBoard() {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
jf = new JFrame("clipboard");
jta = new JTextArea();
jbcopy = new JButton("复制");
jbpaste = new JButton("粘贴");
jbcut = new JButton("剪切");
jt = new JToolBar();
sp = new ScrollPane();
clip = Toolkit.getDefaultToolkit().getSystemClipboard();
// 注册监听器
jbcopy.addActionListener(this);
jbpaste.addActionListener(this);
jbcut.addActionListener(this);
jt.add(jbcopy);
jt.add(jbpaste);
jt.add(jbcut);
sp.add(jta);
jbpaste.setEnabled(false);
jbcut.setEnabled(false);
jf.add(jt, BorderLayout.NORTH);
jf.add(sp, BorderLayout.CENTER);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setSize(300, 300);
jf.setLocation((screenSize.width - 300) / 2,
(screenSize.height - 300) / 2);
jf.setVisible(true);
}
public static void main(String[] args) {
new ClipBoard();
}
@Override
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
if (cmd.equals("复制")) {
if (jta.getSelectedText() != null) {
StringSelection ss = new StringSelection(jta.getSelectedText());
clip.setContents(ss, this);
jbpaste.setEnabled(true);
jbcut.setEnabled(true);
}
} else if (cmd.equals("粘贴")) {
Transferable content = clip.getContents(this);
if (content != null) {
try {
String dstData = (String) content
.getTransferData(DataFlavor.stringFlavor);
jta.append(dstData);
} catch (Exception e1) {
System.out
.println("Couldn't get contents in format: "
+ DataFlavor.stringFlavor
.getHumanPresentableName());
}
}
} else if (cmd.equals("剪切")) {
if (jta.getSelectedText() != null) {
String con = jta.getText();
int start = jta.getSelectionStart();
int end = jta.getSelectionEnd();
String selecttext=jta.getSelectedText();
String newcon = con.substring(0, start)
+ con.substring(end, con.length());
jta.setText(newcon);
StringSelection ss = new StringSelection(selecttext);
clip.setContents(ss, this);
}
}
}
@Override
public void lostOwnership(Clipboard clipboard, Transferable contents) {
System.out.println("Clipboard contents replaced");
}
}