final JLabel keyLable = new JLabel(key); keyLable.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { // TODO Auto-generated method stub //双击选中 if(e.getClickCount() == 2) { String clipboardStr = keyLable.getText(); setClipboardString(clipboardStr); keyLable.setOpaque(true); keyLable.setForeground(Color.BLUE); keyLable.setFont(new Font("Helvetica", Font.BOLD, 14)); } } @Override public void mouseExited(MouseEvent e) { // TODO Auto-generated method stub keyLable.setOpaque(true); keyLable.setForeground(Color.black); keyLable.setFont(new Font("Helvetica", Font.PLAIN, 14)); } });
/** * 获取剪贴板内容(粘贴) */ public String getClipboardString() { //获取系统剪贴板 Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); //获取剪贴板内容 Transferable trans = clipboard.getContents(null); if(trans != null) { //判断剪贴板内容是否支持文本 if(trans.isDataFlavorSupported(DataFlavor.stringFlavor)) { String clipboardStr = null; try { //获取剪贴板的文本内容 clipboardStr = (String) trans.getTransferData(DataFlavor.stringFlavor); } catch (UnsupportedFlavorException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return clipboardStr; } } return null; } /** * 设置剪贴板内容(复制) */ public static void setClipboardString(String str) { //获取协同剪贴板,单例 Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); //封装文本内容 Transferable trans = new StringSelection(str); //把文本内容设置到系统剪贴板上 clipboard.setContents(trans, null); }