/** Get the clipboard contents. */ public static Object getClipboard() { Object result = contents; try { Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard(); Transferable trans = cb.getContents(requestor); // get clipboard content try { Object sysContent = trans.getTransferData(DataFlavor.stringFlavor); if (sysContent != null) { if (sysContent instanceof String) { String str = (String) sysContent; // for empty string: take contents of ClipboardHelper if (str.trim().length() == 0) { result = contents; } else { result = str; } } } } catch (java.io.IOException e) { // e.printStackTrace(); result = contents; } catch (UnsupportedFlavorException e) { // e.printStackTrace(); result = contents; } } catch (Throwable t) { // we're in Communicator or something again.... } return result; }
@Override public void execute(final GUI gui) { final int pre = gui.context.marked.pres[0]; final byte[] txt = ViewData.path(gui.context.data(), pre); // copy path to clipboard final Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard(); clip.setContents(new StringSelection(Token.string(txt)), null); }
/** * Returns the clipboard text. * * @return text */ static final String clip() { // copy selection to clipboard final Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard(); final Transferable tr = clip.getContents(null); if (tr != null) { for (final Object o : BaseXLayout.contents(tr)) return o.toString(); } return ""; }
/** * Description: <br> * Copyright (C), 2005-2008, Yeeku.H.Lee <br> * This program is protected by copyright laws. <br> * Program Name: <br> * Date: * * @author Yeeku.H.Lee [email protected] * @version 1.0 */ public class SimpleClipboard { private Frame f = new Frame("简单的剪贴板程序"); // 获取系统剪贴板 private Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); // 下面是创建本地剪贴板的代码 // Clipboard clipboard = new Clipboard("cb"); // 用于复制文本的文本框 private TextArea jtaCopyTo = new TextArea(5, 20); // 用于粘贴文本的文本框 private TextArea jtaPaste = new TextArea(5, 20); private Button btCopy = new Button("复制"); // 拷贝按钮 private Button btPaste = new Button("粘贴"); // 粘贴按钮 public void init() { Panel p = new Panel(); p.add(btCopy); p.add(btPaste); btCopy.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent event) { // 将一个多行文本域里的字符串封装成StringSelection对象 StringSelection contents = new StringSelection(jtaCopyTo.getText()); // 将StringSelection对象放入剪贴板 clipboard.setContents(contents, null); } }); btPaste.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent event) { // 如果剪贴板中包含stringFlavor内容 if (clipboard.isDataFlavorAvailable(DataFlavor.stringFlavor)) { try { // 取出剪贴板中stringFlavor内容 String content = (String) clipboard.getData(DataFlavor.stringFlavor); jtaPaste.append(content); } catch (Exception e) { e.printStackTrace(); } } } }); // 创建一个水平排列的Box容器 Box box = new Box(BoxLayout.X_AXIS); // 将两个多行文本域放在Box容器中 box.add(jtaCopyTo); box.add(jtaPaste); // 将按钮所在Panel、Box容器添加到Frame窗口中 f.add(p, BorderLayout.SOUTH); f.add(box, BorderLayout.CENTER); f.pack(); f.setVisible(true); } public static void main(String[] args) { new SimpleClipboard().init(); } }
@Override public void actionPerformed(ActionEvent evt) { TreePath path = resultTree.getSelectionPath(); DefaultMutableTreeNode operNode = (DefaultMutableTreeNode) path.getLastPathComponent(); ToStringNodes toStringNodes = new ToStringNodes(); traverseNodes(operNode, toStringNodes); StringSelection selection = new StringSelection(toStringNodes.nodesString.toString()); Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); clipboard.setContents(selection, null); }
private void copyOverviewToClipboard() throws InsufficientDataException { String overview = generateOverviewText(); Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); clipboard.setContents( new StringSelection(overview), new ClipboardOwner() { @Override public void lostOwnership(Clipboard c, Transferable t) {} }); }
public String getClipboardContents() { Transferable contents = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null); if (contents != null && contents.isDataFlavorSupported(DataFlavor.stringFlavor)) { try { return (String) contents.getTransferData(DataFlavor.stringFlavor); } catch (Exception e) { return ""; } } return ""; }
/** * Copies the selected text to the clipboard. * * @return true if text was copied */ final boolean copy() { final String txt = text.copy(); if (txt.isEmpty()) { text.noMark(); return false; } // copy selection to clipboard final Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard(); clip.setContents(new StringSelection(txt), null); return true; }
/** * This method is activated on the Keystrokes we are listening to in this implementation. Here it * listens for Copy and Paste ActionCommands. Selections comprising non-adjacent cells result in * invalid selection and then copy action cannot be performed. Paste is done by aligning the upper * left corner of the selection with the 1st element in the current selection of the JTable. */ public void actionPerformed(ActionEvent e) { if (e.getActionCommand().compareTo("Copy") == 0) { StringBuffer sbf = new StringBuffer(); // Check to ensure we have selected only a contiguous block of // cells int numcols = jTable1.getSelectedColumnCount(); int numrows = jTable1.getSelectedRowCount(); int[] rowsselected = jTable1.getSelectedRows(); int[] colsselected = jTable1.getSelectedColumns(); if (!((numrows - 1 == rowsselected[rowsselected.length - 1] - rowsselected[0] && numrows == rowsselected.length) && (numcols - 1 == colsselected[colsselected.length - 1] - colsselected[0] && numcols == colsselected.length))) { JOptionPane.showMessageDialog( null, "Invalid Copy Selection", "Invalid Copy Selection", JOptionPane.ERROR_MESSAGE); return; } for (int i = 0; i < numrows; i++) { for (int j = 0; j < numcols; j++) { sbf.append(jTable1.getValueAt(rowsselected[i], colsselected[j])); if (j < numcols - 1) sbf.append("\t"); } sbf.append("\n"); } stsel = new StringSelection(sbf.toString()); system = Toolkit.getDefaultToolkit().getSystemClipboard(); system.setContents(stsel, stsel); } if (e.getActionCommand().compareTo("Paste") == 0) { System.out.println("Trying to Paste"); int startRow = (jTable1.getSelectedRows())[0]; int startCol = (jTable1.getSelectedColumns())[0]; try { String trstring = (String) (system.getContents(this).getTransferData(DataFlavor.stringFlavor)); System.out.println("String is:" + trstring); StringTokenizer st1 = new StringTokenizer(trstring, "\n"); for (int i = 0; st1.hasMoreTokens(); i++) { rowstring = st1.nextToken(); StringTokenizer st2 = new StringTokenizer(rowstring, "\t"); for (int j = 0; st2.hasMoreTokens(); j++) { value = (String) st2.nextToken(); if (startRow + i < jTable1.getRowCount() && startCol + j < jTable1.getColumnCount()) jTable1.setValueAt(value, startRow + i, startCol + j); System.out.println( "Putting " + value + "at row = " + startRow + i + "column = " + startCol + j); } } } catch (Exception ex) { ex.printStackTrace(); } } }
/** * The Excel Adapter is constructed with a JTable on which it enables Copy-Paste and acts as a * Clipboard listener. */ public ExcelAdapter(JTable myJTable) { jTable1 = myJTable; KeyStroke copy = KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.CTRL_MASK, false); // Identifying the copy KeyStroke user can modify this // to copy on some other Key combination. KeyStroke paste = KeyStroke.getKeyStroke(KeyEvent.VK_V, ActionEvent.CTRL_MASK, false); // Identifying the Paste KeyStroke user can modify this // to copy on some other Key combination. jTable1.registerKeyboardAction(this, "Copy", copy, JComponent.WHEN_FOCUSED); jTable1.registerKeyboardAction(this, "Paste", paste, JComponent.WHEN_FOCUSED); system = Toolkit.getDefaultToolkit().getSystemClipboard(); }
/** * Returns the clipboard text. * * @return text */ private static String clip() { // copy selection to clipboard final Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard(); final Transferable tr = clip.getContents(null); if (tr != null) { final ArrayList<Object> contents = BaseXLayout.contents(tr); if (!contents.isEmpty()) return contents.get(0).toString(); } else { Util.debug("Clipboard has no contents."); } return null; }
@Override public void exportToClipboard(JComponent comp, Clipboard clip, int action) throws IllegalStateException { TreePath[] paths = resultTree.getSelectionPaths(); ToStringNodes toStringNodes = new ToStringNodes(); for (TreePath path : paths) { DefaultMutableTreeNode operNode = (DefaultMutableTreeNode) path.getLastPathComponent(); toStringNodes.processNode(operNode); } StringSelection selection = new StringSelection(toStringNodes.nodesString.toString()); Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); clipboard.setContents(selection, null); }
/** Set the clipboard contents. */ public static void setClipboard(Object arg) { // use JDK clipboard in 1.1 if it is a string if (arg instanceof String) { try { Toolkit toolkit = Toolkit.getDefaultToolkit(); Clipboard cb = toolkit.getSystemClipboard(); StringSelection s = new StringSelection((String) arg); cb.setContents(s, s); } catch (Throwable t) { // we're in Communicator or something again.... } } else { try { Toolkit toolkit = Toolkit.getDefaultToolkit(); Clipboard cb = toolkit.getSystemClipboard(); StringSelection s = new StringSelection(""); cb.setContents(s, s); } catch (Throwable t) { // we're in Communicator or something again.... } } contents = arg; }
public void toClipBoard() { try { Toolkit.getDefaultToolkit() .getSystemClipboard() .setContents(new StringSelection(PArray.cat(M)), null); } catch (IllegalStateException e) { JOptionPane.showConfirmDialog( null, "Copy to clipboard failed : " + e.getMessage(), "Error", JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE); } }
private void dumpFlavorsOld(Transferable t) { DataFlavor[] dfa = t.getTransferDataFlavors(); if (dfa != null) { if (dfa.length == 0) { JConfig.log().logVerboseDebug("Trying a second attack..."); try { Clipboard sysClip = Toolkit.getDefaultToolkit().getSystemClipboard(); Transferable t2 = sysClip.getContents(null); StringBuffer stBuff; stBuff = getTransferData(t2); JConfig.log().logVerboseDebug("Check out: " + stBuff); } catch (Exception e) { JConfig.log().handleException("Caught: " + e, e); } JConfig.log().logVerboseDebug("Done trying a second attack..."); } } dumpDataFlavors(dfa); }
public void run(String arg) { Frame[] niframes = WindowManager.getNonImageWindows(); String[] titles = new String[niframes.length + 1]; for (int i = 0; i < niframes.length; i++) { titles[i] = niframes[i].getTitle(); } titles[niframes.length] = "Clipboard"; GenericDialog gd = new GenericDialog("Windows"); boolean importfile = false; gd.addCheckbox("Import from file?", importfile); gd.addChoice("Windows", titles, titles[0]); boolean hasxvals = false; gd.addCheckbox("X Vals Column?", hasxvals); boolean multix = false; gd.addCheckbox("Multi_X_Columns?", multix); boolean skipendzeros = false; gd.addCheckbox("Skip_end_zeros?", skipendzeros); String[] delimiters = {"Tab", "Comma", "Space"}; gd.addChoice("Delimiter", delimiters, delimiters[0]); gd.showDialog(); if (gd.wasCanceled()) { return; } importfile = gd.getNextBoolean(); int index = gd.getNextChoiceIndex(); hasxvals = gd.getNextBoolean(); multix = gd.getNextBoolean(); skipendzeros = gd.getNextBoolean(); int delimindex = gd.getNextChoiceIndex(); if (multix) hasxvals = true; String textdata = ""; if (importfile) { OpenDialog od = new OpenDialog("Open File", "", ".txt"); String directory = od.getDirectory(); String name = od.getFileName(); if (name == null) { return; } try { File infile = new File(directory + name); BufferedReader b = new BufferedReader(new FileReader(infile)); textdata = (new jdataio()).readstringfile(b); b.close(); } catch (IOException e) { return; } } else { if (index == niframes.length) { // here we get the data from the clipboard Transferable t = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null); try { if (t != null && t.isDataFlavorSupported(DataFlavor.stringFlavor)) { textdata = (String) t.getTransferData(DataFlavor.stringFlavor); } } catch (UnsupportedFlavorException e) { } catch (IOException e) { } if (textdata.equals("")) { IJ.error("Error copying from clipboard."); return; } } else { if (niframes[index] instanceof Editor) { Editor tw = (Editor) niframes[index]; textdata = tw.getText(); } else { if (niframes[index] instanceof TextWindow) { TextWindow tw = (TextWindow) niframes[index]; textdata = tw.getTextPanel().getText(); } else { IJ.showMessage("Not a valid text window"); return; } } } } if (textdata == null) { IJ.showMessage("Error in Obtaining String"); return; } if (textdata.indexOf("\r") >= 0) { textdata = textdata.replace('\r', '\n'); } char[] delims = {'\t', ',', ' '}; delimit_string ds = new delimit_string(delims[delimindex]); String[] rows = ds.getrows(textdata); int lines = rows.length; int columns = ds.getnumcolumns(rows[0]); int ycolumns = columns; if (hasxvals) { if (multix) { ycolumns /= 2; } else { ycolumns--; } } if (multix) { float[][] ydata = new float[ycolumns][lines]; float[][] xdata = new float[ycolumns][lines]; for (int i = 0; i < lines; i++) { float[] temp = ds.delim2float(rows[i], columns); for (int j = 0; j < ycolumns; j++) { ydata[j][i] = temp[2 * j + 1]; xdata[j][i] = temp[2 * j]; } } int[] npts = new int[ycolumns]; for (int i = 0; i < ycolumns; i++) { npts[i] = lines; } if (skipendzeros) { for (int i = 0; i < ycolumns; i++) { int counter = lines - 1; while ((xdata[i][counter] == 0.0f || Float.isNaN(xdata[i][counter])) && counter > 0) { xdata[i][counter] = 0.0f; ydata[i][counter] = 0.0f; npts[i]--; counter--; } } } (new PlotWindow4("Text Plot", "x", "y", xdata, ydata, npts)).draw(); } else { float[][] tempydata = new float[ycolumns][lines]; float[] tempxdata = new float[lines]; float[][] xdata = null; float[][] ydata = null; int startcolumn = 0; if (hasxvals) startcolumn = 1; for (int i = 0; i < lines; i++) { float[] temp = ds.delim2float(rows[i], columns); if (hasxvals) { tempxdata[i] = temp[0]; } else { tempxdata[i] = (float) (i + 1); } for (int j = 0; j < ycolumns; j++) { tempydata[j][i] = temp[j + startcolumn]; } } int[] npts = new int[ycolumns]; npts[0] = lines; if (skipendzeros) { int maxpts = 0; for (int i = 0; i < ycolumns; i++) { int counter = lines - 1; npts[i] = lines; while ((tempydata[i][counter] == 0.0f || Float.isNaN(tempydata[i][counter])) && counter > 0) { npts[i]--; counter--; } if (npts[i] > maxpts) maxpts = npts[i]; IJ.log("" + npts[i]); } ydata = new float[ycolumns][maxpts]; xdata = new float[ycolumns][maxpts]; for (int i = 0; i < ycolumns; i++) { // npts[i]=npts[0]; System.arraycopy(tempxdata, 0, xdata[i], 0, npts[i]); System.arraycopy(tempydata[i], 0, ydata[i], 0, npts[i]); } } else { ydata = tempydata; xdata = new float[ycolumns][]; for (int i = 0; i < ycolumns; i++) { npts[i] = npts[0]; xdata[i] = tempxdata.clone(); } } (new PlotWindow4("Text Plot", "x", "y", xdata, ydata, npts)).draw(); } }
public void drop(DropTargetDropEvent dtde) { Transferable t = dtde.getTransferable(); StringBuffer dropData = null; DataFlavor dtf; JConfig.log().logVerboseDebug("Dropping!"); if (t.getTransferDataFlavors().length == 0) { Clipboard sysClip = Toolkit.getDefaultToolkit().getSystemClipboard(); Transferable t2 = sysClip.getContents(null); DataFlavor[] dfa2; int j; JConfig.log().logDebug("Dropped 0 data flavors, trying clipboard."); dfa2 = null; if (t2 != null) { JConfig.log().logVerboseDebug("t2 is not null: " + t2); dfa2 = t2.getTransferDataFlavors(); JConfig.log().logVerboseDebug("Back from getTransferDataFlavors()!"); } else { JConfig.log().logVerboseDebug("t2 is null!"); } if (JConfig.queryConfiguration("debug.uber", "false").equals("true")) { if (dfa2 != null) { if (dfa2.length == 0) { JConfig.log().logVerboseDebug("Length is still zero!"); } for (j = 0; j < dfa2.length; j++) { JConfig.log() .logVerboseDebug("Flavah " + j + " == " + dfa2[j].getHumanPresentableName()); JConfig.log().logVerboseDebug("Flavah/mime " + j + " == " + dfa2[j].getMimeType()); } } else { JConfig.log().logVerboseDebug("Flavahs supported: none!\n"); } } } if (JConfig.queryConfiguration("debug.uber", "false").equals("true") && JConfig.debugging) dumpFlavorsOld(t); dtf = testAllFlavors(t); if (dtf != null) { JConfig.log().logVerboseDebug("Accepting!"); acceptDrop(dtde); dropData = getTransferData(t); dtde.dropComplete(true); dtde.getDropTargetContext().dropComplete(true); if (dropData != null) { if (handler != null) { handler.receiveDropString(dropData); } } } else { JConfig.log().logVerboseDebug("Rejecting!"); dtde.rejectDrop(); handler.receiveDropString(dropData); } }
/** * Paste the contents of the clipboard into the console buffer * * @return true if clipboard contents pasted */ public boolean paste() throws IOException { Clipboard clipboard; try { // May throw ugly exception on system without X clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); } catch (Exception e) { return false; } if (clipboard == null) { return false; } Transferable transferable = clipboard.getContents(null); if (transferable == null) { return false; } try { Object content = transferable.getTransferData(DataFlavor.plainTextFlavor); /* * This fix was suggested in bug #1060649 at * http://sourceforge.net/tracker/index.php?func=detail&aid=1060649&group_id=64033&atid=506056 * to get around the deprecated DataFlavor.plainTextFlavor, but it * raises a UnsupportedFlavorException on Mac OS X */ if (content == null) { try { content = new DataFlavor().getReaderForText(transferable); } catch (Exception e) { } } if (content == null) { return false; } String value; if (content instanceof Reader) { // TODO: we might want instead connect to the input stream // so we can interpret individual lines value = ""; String line = null; for (BufferedReader read = new BufferedReader((Reader) content); (line = read.readLine()) != null; ) { if (value.length() > 0) { value += "\n"; } value += line; } } else { value = content.toString(); } if (value == null) { return true; } putString(value); return true; } catch (UnsupportedFlavorException ufe) { if (debugger != null) debug(ufe + ""); return false; } }
/** * This class provides static layout and paint helper methods which are used all over the GUI. * * @author BaseX Team 2005-16, BSD License * @author Christian Gruen */ public final class BaseXLayout { /** Desktop hints. */ private static final Map<?, ?> HINTS = (Map<?, ?>) Toolkit.getDefaultToolkit().getDesktopProperty("awt.font.desktophints"); /** Flag for adding rendering hints. */ private static boolean hints = true; /** Shortcut string for meta key. */ private static final String META = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask() == InputEvent.META_MASK ? "meta" : "ctrl"; /** Key listener for global shortcuts. */ private static KeyAdapter keys; /** Private constructor. */ private BaseXLayout() {} /** * Sets the help text for the specified component. * * @param cont input container */ static void focus(final Component cont) { final GUI gui = gui(cont); if (gui == null) return; if (gui.gopts.get(GUIOptions.MOUSEFOCUS) && cont.isEnabled()) cont.requestFocusInWindow(); } /** * Set desktop hints (not supported by all platforms). * * @param g graphics reference */ public static void hints(final Graphics g) { if (HINTS != null && hints) { try { ((Graphics2D) g).addRenderingHints(HINTS); } catch (final Exception ex) { Util.stack(ex); hints = false; } } } /** * Activates graphics anti-aliasing. * * @param g graphics reference * @return graphics reference */ public static Graphics2D antiAlias(final Graphics g) { final Graphics2D g2 = (Graphics2D) g; g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); return g2; } /** * Returns the GUI reference of the specified container. * * @param cont input container * @return gui */ private static GUI gui(final Component cont) { final Container c = cont.getParent(); return c == null || c instanceof GUI ? (GUI) c : gui(c); } /** * Sets the scaled component width, adopting the original component height. * * @param comp component * @param w width */ public static void setWidth(final Component comp, final int w) { comp.setPreferredSize(new Dimension((int) (w * scale), comp.getPreferredSize().height)); } /** * Sets the scaled component height, adopting the original component width. * * @param comp component * @param h height */ public static void setHeight(final Component comp, final int h) { comp.setPreferredSize(new Dimension(comp.getPreferredSize().width, (int) (h * scale))); } /** * Returns a border with the specified insets. * * @param t top distance * @param l left distance * @param b bottom distance * @param r right distance * @return border */ public static EmptyBorder border(final int t, final int l, final int b, final int r) { return new EmptyBorder( (int) (t * ascale), (int) (l * ascale), (int) (b * ascale), (int) (r * ascale)); } /** * Adds drag and drop functionality. * * @param comp component * @param dnd drag and drop handler */ public static void addDrop(final JComponent comp, final DropHandler dnd) { comp.setDropTarget( new DropTarget(comp, DnDConstants.ACTION_COPY_OR_MOVE, null, true, null) { @Override public synchronized void drop(final DropTargetDropEvent dtde) { dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE); final Transferable tr = dtde.getTransferable(); for (final Object o : contents(tr)) dnd.drop(o); comp.requestFocusInWindow(); } }); } /** * Returns a keystroke for the specified string. * * @param cmd command * @return keystroke */ public static KeyStroke keyStroke(final GUICommand cmd) { final Object sc = cmd.shortcuts(); if (sc == null) return null; final String scut; if (sc instanceof BaseXKeys[]) { final BaseXKeys[] scs = (BaseXKeys[]) sc; if (scs.length == 0) return null; scut = scs[0].shortCut(); } else { scut = Util.info(sc, META); } final KeyStroke ks = KeyStroke.getKeyStroke(scut); if (ks == null) Util.errln("Could not assign shortcut: " + sc + " / " + scut); return ks; } /** * Sets a mnemomic for the specified button. * * @param b button * @param mnem mnemonics that have already been assigned */ public static void setMnemonic(final AbstractButton b, final StringBuilder mnem) { // do not set mnemonics for Mac! Alt+key used for special characters. if (Prop.MAC) return; // find and assign unused mnemomic final String label = b.getText(); final int ll = label.length(); for (int l = 0; l < ll; l++) { final char ch = Character.toLowerCase(label.charAt(l)); if (!letter(ch) || mnem.indexOf(Character.toString(ch)) != -1) continue; b.setMnemonic(ch); mnem.append(ch); break; } } /** * Returns the contents of the specified transferable. * * @param tr transferable * @return contents */ @SuppressWarnings("unchecked") public static ArrayList<Object> contents(final Transferable tr) { final ArrayList<Object> list = new ArrayList<>(); try { if (tr.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) { for (final File fl : (List<File>) tr.getTransferData(DataFlavor.javaFileListFlavor)) list.add(fl); } else if (tr.isDataFlavorSupported(DataFlavor.stringFlavor)) { list.add(tr.getTransferData(DataFlavor.stringFlavor)); } } catch (final Exception ex) { Util.stack(ex); } return list; } /** * Copies the specified string to the clipboard. * * @param text text */ public static void copy(final String text) { Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection(text), null); } /** * Drag and drop handler. * * @author BaseX Team 2005-16, BSD License * @author Christian Gruen */ public interface DropHandler { /** * Drops a file. * * @param obj object to be dropped */ void drop(final Object obj); } /** * Adds default interactions to the specified component. * * @param comp component * @param win parent window */ public static void addInteraction(final Component comp, final Window win) { comp.addMouseListener( new MouseAdapter() { @Override public void mouseEntered(final MouseEvent e) { focus(comp); } }); if (win instanceof BaseXDialog) { // add default keys final BaseXDialog d = (BaseXDialog) win; comp.addKeyListener( new KeyAdapter() { @Override public void keyPressed(final KeyEvent e) { final Object s = e.getSource(); if (s instanceof BaseXCombo && ((BaseXCombo) s).isPopupVisible()) return; // do not key close dialog if button or editor is focused if (ENTER.is(e) && !(s instanceof BaseXButton || s instanceof TextPanel)) { d.close(); } else if (ESCAPE.is(e)) { // do not cancel dialog if search bar is opened boolean close = true; if (s instanceof TextPanel) { final SearchBar bar = ((TextPanel) s).getSearch(); close = bar == null || !bar.deactivate(true); } if (close) d.cancel(); } } }); return; } if (win instanceof GUI) { comp.addKeyListener(globalShortcuts((GUI) win)); } else { throw Util.notExpected("Reference to main window expected."); } } /** * Returns or creates a new key listener for global shortcuts. * * @param gui gui reference * @return key listener */ private static KeyAdapter globalShortcuts(final GUI gui) { if (keys == null) { keys = new KeyAdapter() { @Override public void keyPressed(final KeyEvent e) { // browse back/forward if (gui.context.data() != null) { if (GOBACK.is(e)) { GUIMenuCmd.C_GOBACK.execute(gui); } else if (GOFORWARD.is(e)) { GUIMenuCmd.C_GOFORWARD.execute(gui); } else if (GOUP.is(e)) { GUIMenuCmd.C_GOUP.execute(gui); } else if (GOHOME.is(e)) { GUIMenuCmd.C_GOHOME.execute(gui); } } // jump to input bar if (INPUTBAR.is(e)) gui.input.requestFocusInWindow(); // change font size final int fs = gui.gopts.get(GUIOptions.FONTSIZE); int nfs = fs; if (INCFONT1.is(e) || INCFONT2.is(e)) { nfs = fs + 1; } else if (DECFONT.is(e)) { nfs = Math.max(1, fs - 1); } else if (NORMFONT.is(e)) { nfs = 13; } if (fs != nfs) { gui.gopts.set(GUIOptions.FONTSIZE, nfs); gui.updateLayout(); } } }; } return keys; } /** * Adds human readable shortcuts to the specified string. * * @param str text of tooltip * @param sc shortcut * @return tooltip */ public static String addShortcut(final String str, final String sc) { if (sc == null || str == null) return str; final StringBuilder sb = new StringBuilder(); for (final String s : sc.split(" ")) { String t = "%".equals(s) ? Prop.MAC ? "meta" : "control" : s; if (t.length() != 1) t = Toolkit.getProperty("AWT." + t.toLowerCase(Locale.ENGLISH), t); sb.append('+').append(t); } return str + " (" + sb.substring(1) + ')'; } /** * Returns the value of the specified pre value and attribute. * * @param val value to be evaluated * @return value as string */ public static String value(final double val) { return string(chopNumber(token(val))); } /** * Draws a colored cell. * * @param g graphics reference * @param xs horizontal start position * @param xe horizontal end position * @param ys vertical start position * @param ye vertical end position * @param focus highlighting flag */ public static void drawCell( final Graphics g, final int xs, final int xe, final int ys, final int ye, final boolean focus) { g.setColor(gray); g.drawRect(xs, ys, xe - xs - 1, ye - ys - 1); g.setColor(BACK); g.drawRect(xs + 1, ys + 1, xe - xs - 3, ye - ys - 3); g.setColor(focus ? lgray : BACK); g.fillRect(xs + 1, ys + 1, xe - xs - 2, ye - ys - 2); } /** * Draws a centered string to the panel. * * @param g graphics reference * @param text text to be painted * @param w panel width * @param y vertical position */ public static void drawCenter(final Graphics g, final String text, final int w, final int y) { g.drawString(text, (w - width(g, text)) / 2, y); } /** * Draws a visualization tooltip. * * @param g graphics reference * @param tt tooltip label * @param x horizontal position * @param y vertical position * @param w width * @param c color color depth */ public static void drawTooltip( final Graphics g, final String tt, final int x, final int y, final int w, final int c) { final int tw = width(g, tt); final int th = g.getFontMetrics().getHeight(); final int xx = Math.min(w - tw - 8, x); g.setColor(color(c)); g.fillRect(xx - 1, y - th, tw + 4, th); g.setColor(BACK); g.drawString(tt, xx, y - 4); } /** * Returns the width of the specified text. * * @param g graphics reference * @param s string to be evaluated * @return string width */ public static int width(final Graphics g, final String s) { return g.getFontMetrics().stringWidth(s); } /** * Draws the specified string. * * @param g graphics reference * @param s text * @param x x coordinate * @param y y coordinate * @param w width * @param fs font size */ public static void chopString( final Graphics g, final byte[] s, final int x, final int y, final int w, final int fs) { if (w < 12) return; final int[] cw = fontWidths(g.getFont()); int j = s.length; try { int l = 0; int fw = 0; for (int k = 0; k < j; k += l) { final int ww = width(g, cw, cp(s, k)); if (fw + ww >= w - 4) { j = Math.max(1, k - l); if (k > 1) fw -= width(g, cw, cp(s, k - 1)); g.drawString("..", x + fw, y + fs); break; } fw += ww; l = cl(s, k); } } catch (final Exception ex) { Util.debug(ex); } g.drawString(string(s, 0, j), x, y + fs); } /** * Returns the width of the specified text. Cached font widths are used to speed up calculation. * * @param g graphics reference * @param s string to be evaluated * @return string width */ public static int width(final Graphics g, final byte[] s) { final int[] cw = fontWidths(g.getFont()); final int l = s.length; int fw = 0; try { // ignore faulty character sets for (int k = 0; k < l; k += cl(s, k)) fw += width(g, cw, cp(s, k)); } catch (final Exception ex) { Util.debug(ex); } return fw; } /** * Returns the character width of the specified character. * * @param g graphics reference * @param cw array with character widths * @param c character * @return character width */ public static int width(final Graphics g, final int[] cw, final int c) { return c >= cw.length ? g.getFontMetrics().charWidth(c) : cw[c]; } }
public static void setClipboardText(String text) { Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection(text), null); }
public void actionPerformed(ActionEvent e) { if (isDirectorySelected()) { File dir = getDirectory(); if (dir != null) { try { // Strip trailing ".." dir = ShellFolder.getNormalizedFile(dir); } catch (IOException ex) { // Ok, use f as is } changeDirectory(dir); return; } } JFileChooser chooser = getFileChooser(); String filename = getFileName(); FileSystemView fs = chooser.getFileSystemView(); File dir = chooser.getCurrentDirectory(); if (filename != null) { // Remove whitespaces from end of filename int i = filename.length() - 1; while (i >= 0 && filename.charAt(i) <= ' ') { i--; } filename = filename.substring(0, i + 1); } if (filename == null || filename.length() == 0) { // no file selected, multiple selection off, therefore cancel the approve action resetGlobFilter(); return; } File selectedFile = null; File[] selectedFiles = null; // Unix: Resolve '~' to user's home directory if (File.separatorChar == '/') { if (filename.startsWith("~/")) { filename = System.getProperty("user.home") + filename.substring(1); } else if (filename.equals("~")) { filename = System.getProperty("user.home"); } } if (chooser.isMultiSelectionEnabled() && filename.length() > 1 && filename.charAt(0) == '"' && filename.charAt(filename.length() - 1) == '"') { List<File> fList = new ArrayList<File>(); String[] files = filename.substring(1, filename.length() - 1).split("\" \""); // Optimize searching files by names in "children" array Arrays.sort(files); File[] children = null; int childIndex = 0; for (String str : files) { File file = fs.createFileObject(str); if (!file.isAbsolute()) { if (children == null) { children = fs.getFiles(dir, false); Arrays.sort(children); } for (int k = 0; k < children.length; k++) { int l = (childIndex + k) % children.length; if (children[l].getName().equals(str)) { file = children[l]; childIndex = l + 1; break; } } } fList.add(file); } if (!fList.isEmpty()) { selectedFiles = fList.toArray(new File[fList.size()]); } resetGlobFilter(); } else { selectedFile = fs.createFileObject(filename); if (!selectedFile.isAbsolute()) { selectedFile = fs.getChild(dir, filename); } // check for wildcard pattern FileFilter currentFilter = chooser.getFileFilter(); if (!selectedFile.exists() && isGlobPattern(filename)) { changeDirectory(selectedFile.getParentFile()); if (globFilter == null) { globFilter = new GlobFilter(); } try { globFilter.setPattern(selectedFile.getName()); if (!(currentFilter instanceof GlobFilter)) { actualFileFilter = currentFilter; } chooser.setFileFilter(null); chooser.setFileFilter(globFilter); return; } catch (PatternSyntaxException pse) { // Not a valid glob pattern. Abandon filter. } } resetGlobFilter(); // Check for directory change action boolean isDir = (selectedFile != null && selectedFile.isDirectory()); boolean isTrav = (selectedFile != null && chooser.isTraversable(selectedFile)); boolean isDirSelEnabled = chooser.isDirectorySelectionEnabled(); boolean isFileSelEnabled = chooser.isFileSelectionEnabled(); boolean isCtrl = (e != null && (e.getModifiers() & Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()) != 0); if (isDir && isTrav && (isCtrl || !isDirSelEnabled)) { changeDirectory(selectedFile); return; } else if ((isDir || !isFileSelEnabled) && (!isDir || !isDirSelEnabled) && (!isDirSelEnabled || selectedFile.exists())) { selectedFile = null; } } if (selectedFiles != null || selectedFile != null) { if (selectedFiles != null || chooser.isMultiSelectionEnabled()) { if (selectedFiles == null) { selectedFiles = new File[] {selectedFile}; } chooser.setSelectedFiles(selectedFiles); // Do it again. This is a fix for bug 4949273 to force the // selected value in case the ListSelectionModel clears it // for non-existing file names. chooser.setSelectedFiles(selectedFiles); } else { chooser.setSelectedFile(selectedFile); } chooser.approveSelection(); } else { if (chooser.isMultiSelectionEnabled()) { chooser.setSelectedFiles(null); } else { chooser.setSelectedFile(null); } chooser.cancelSelection(); } }
public void copySelection() { Toolkit.getDefaultToolkit() .getSystemClipboard() .setContents(new StringSelection(getSelectedText()), this); }
public void beep() { if (mySettingsProvider.audibleBell()) { Toolkit.getDefaultToolkit().beep(); } }
void setUpClipboard() { myClipboard = Toolkit.getDefaultToolkit().getSystemSelection(); if (myClipboard == null) { myClipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); } }
public HtmlBlock( int listNesting, Color background, RenderState parentRenderState, boolean opaque, HtmlParserContext pcontext, FrameContext frameContext) { this.frameContext = frameContext; this.rblock = new RBlock(listNesting, parentRenderState, pcontext, frameContext, this, null); this.setOpaque(opaque); this.setBackground(background); ActionListener actionListener = new ActionListener() { public void actionPerformed(ActionEvent e) { String command = e.getActionCommand(); if ("copy".equals(command)) { String selection = HtmlBlock.this.getSelectionText(); if (selection != null) { Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); clipboard.setContents(new StringSelection(selection), HtmlBlock.this); } } } }; this.registerKeyboardAction( actionListener, "copy", KeyStroke.getKeyStroke(KeyEvent.VK_COPY, 0), JComponent.WHEN_FOCUSED); this.registerKeyboardAction( actionListener, "copy", KeyStroke.getKeyStroke(KeyEvent.VK_C, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()), JComponent.WHEN_FOCUSED); this.addMouseListener( new MouseListener() { public void mouseClicked(MouseEvent e) { onMouseClick(e); } public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) { onMouseExited(e); } public void mousePressed(MouseEvent e) { onMousePressed(e); } public void mouseReleased(MouseEvent e) { onMouseReleased(e); } }); this.addMouseMotionListener( new MouseMotionListener() { /* (non-Javadoc) * @see java.awt.event.MouseMotionListener#mouseDragged(java.awt.event.MouseEvent) */ public void mouseDragged(MouseEvent e) { onMouseDragged(e); } /* (non-Javadoc) * @see java.awt.event.MouseMotionListener#mouseMoved(java.awt.event.MouseEvent) */ public void mouseMoved(MouseEvent arg0) {} }); }