List of usage examples for javax.swing TransferHandler TransferHandler
protected TransferHandler()
From source file:BasicDnD.java
public BasicDnD() { super(new BorderLayout()); JPanel leftPanel = createVerticalBoxPanel(); JPanel rightPanel = createVerticalBoxPanel(); // Create a table model. DefaultTableModel tm = new DefaultTableModel(); tm.addColumn("Column 0"); tm.addColumn("Column 1"); tm.addColumn("Column 2"); tm.addColumn("Column 3"); tm.addRow(new String[] { "Table 00", "Table 01", "Table 02", "Table 03" }); tm.addRow(new String[] { "Table 10", "Table 11", "Table 12", "Table 13" }); tm.addRow(new String[] { "Table 20", "Table 21", "Table 22", "Table 23" }); tm.addRow(new String[] { "Table 30", "Table 31", "Table 32", "Table 33" }); // LEFT COLUMN // Use the table model to create a table. table = new JTable(tm); leftPanel.add(createPanelForComponent(table, "JTable")); // Create a color chooser. colorChooser = new JColorChooser(); leftPanel.add(createPanelForComponent(colorChooser, "JColorChooser")); // RIGHT COLUMN // Create a textfield. textField = new JTextField(30); textField.setText("Favorite foods:\nPizza, Moussaka, Pot roast"); rightPanel.add(createPanelForComponent(textField, "JTextField")); // Create a scrolled text area. textArea = new JTextArea(5, 30); textArea.setText("Favorite shows:\nBuffy, Alias, Angel"); JScrollPane scrollPane = new JScrollPane(textArea); rightPanel.add(createPanelForComponent(scrollPane, "JTextArea")); // Create a list model and a list. DefaultListModel listModel = new DefaultListModel(); listModel.addElement("Martha Washington"); listModel.addElement("Abigail Adams"); listModel.addElement("Martha Randolph"); listModel.addElement("Dolley Madison"); listModel.addElement("Elizabeth Monroe"); listModel.addElement("Louisa Adams"); listModel.addElement("Emily Donelson"); list = new JList(listModel); list.setVisibleRowCount(-1);//from w w w . j a v a 2 s . c o m list.getSelectionModel().setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); list.setTransferHandler(new TransferHandler() { public boolean canImport(TransferHandler.TransferSupport info) { // we only import Strings if (!info.isDataFlavorSupported(DataFlavor.stringFlavor)) { return false; } JList.DropLocation dl = (JList.DropLocation) info.getDropLocation(); if (dl.getIndex() == -1) { return false; } return true; } public boolean importData(TransferHandler.TransferSupport info) { if (!info.isDrop()) { return false; } // Check for String flavor if (!info.isDataFlavorSupported(DataFlavor.stringFlavor)) { displayDropLocation("List doesn't accept a drop of this type."); return false; } JList.DropLocation dl = (JList.DropLocation) info.getDropLocation(); DefaultListModel listModel = (DefaultListModel) list.getModel(); int index = dl.getIndex(); boolean insert = dl.isInsert(); // Get the current string under the drop. String value = (String) listModel.getElementAt(index); // Get the string that is being dropped. Transferable t = info.getTransferable(); String data; try { data = (String) t.getTransferData(DataFlavor.stringFlavor); } catch (Exception e) { return false; } // Display a dialog with the drop information. String dropValue = "\"" + data + "\" dropped "; if (dl.isInsert()) { if (dl.getIndex() == 0) { displayDropLocation(dropValue + "at beginning of list"); } else if (dl.getIndex() >= list.getModel().getSize()) { displayDropLocation(dropValue + "at end of list"); } else { String value1 = (String) list.getModel().getElementAt(dl.getIndex() - 1); String value2 = (String) list.getModel().getElementAt(dl.getIndex()); displayDropLocation(dropValue + "between \"" + value1 + "\" and \"" + value2 + "\""); } } else { displayDropLocation(dropValue + "on top of " + "\"" + value + "\""); } /** * This is commented out for the basicdemo.html tutorial page. * If you * add this code snippet back and delete the * "return false;" line, the * list will accept drops * of type string. // Perform the actual * import. if (insert) { listModel.add(index, data); } else { * listModel.set(index, data); } return true; */ return false; } public int getSourceActions(JComponent c) { return COPY; } protected Transferable createTransferable(JComponent c) { JList list = (JList) c; Object[] values = list.getSelectedValues(); StringBuffer buff = new StringBuffer(); for (int i = 0; i < values.length; i++) { Object val = values[i]; buff.append(val == null ? "" : val.toString()); if (i != values.length - 1) { buff.append("\n"); } } return new StringSelection(buff.toString()); } }); list.setDropMode(DropMode.ON_OR_INSERT); JScrollPane listView = new JScrollPane(list); listView.setPreferredSize(new Dimension(300, 100)); rightPanel.add(createPanelForComponent(listView, "JList")); // Create a tree. DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("Mia Familia"); DefaultMutableTreeNode sharon = new DefaultMutableTreeNode("Sharon"); rootNode.add(sharon); DefaultMutableTreeNode maya = new DefaultMutableTreeNode("Maya"); sharon.add(maya); DefaultMutableTreeNode anya = new DefaultMutableTreeNode("Anya"); sharon.add(anya); sharon.add(new DefaultMutableTreeNode("Bongo")); maya.add(new DefaultMutableTreeNode("Muffin")); anya.add(new DefaultMutableTreeNode("Winky")); DefaultTreeModel model = new DefaultTreeModel(rootNode); tree = new JTree(model); tree.getSelectionModel().setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION); JScrollPane treeView = new JScrollPane(tree); treeView.setPreferredSize(new Dimension(300, 100)); rightPanel.add(createPanelForComponent(treeView, "JTree")); // Create the toggle button. toggleDnD = new JCheckBox("Turn on Drag and Drop"); toggleDnD.setActionCommand("toggleDnD"); toggleDnD.addActionListener(this); JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftPanel, rightPanel); splitPane.setOneTouchExpandable(true); add(splitPane, BorderLayout.CENTER); add(toggleDnD, BorderLayout.PAGE_END); setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); }
From source file:LocationSensitiveDemo.java
public LocationSensitiveDemo() { super("Location Sensitive Drag and Drop Demo"); treeModel = getDefaultTreeModel();/*from w w w. jav a2 s .com*/ tree = new JTree(treeModel); tree.setBorder(BorderFactory.createEmptyBorder(2, 4, 2, 4)); tree.getSelectionModel().setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION); tree.setDropMode(DropMode.ON); namesPath = tree.getPathForRow(2); tree.expandRow(2); tree.expandRow(1); tree.setRowHeight(0); tree.setTransferHandler(new TransferHandler() { public boolean canImport(TransferHandler.TransferSupport info) { // for the demo, we'll only support drops (not clipboard paste) if (!info.isDrop()) { return false; } String item = (String) indicateCombo.getSelectedItem(); if (item.equals("Always")) { info.setShowDropLocation(true); } else if (item.equals("Never")) { info.setShowDropLocation(false); } // we only import Strings if (!info.isDataFlavorSupported(DataFlavor.stringFlavor)) { return false; } // fetch the drop location JTree.DropLocation dl = (JTree.DropLocation) info.getDropLocation(); TreePath path = dl.getPath(); // we don't support invalid paths or descendants of the names folder if (path == null || namesPath.isDescendant(path)) { return false; } return true; } public boolean importData(TransferHandler.TransferSupport info) { // if we can't handle the import, say so if (!canImport(info)) { return false; } // fetch the drop location JTree.DropLocation dl = (JTree.DropLocation) info.getDropLocation(); // fetch the path and child index from the drop location TreePath path = dl.getPath(); int childIndex = dl.getChildIndex(); // fetch the data and bail if this fails String data; try { data = (String) info.getTransferable().getTransferData(DataFlavor.stringFlavor); } catch (UnsupportedFlavorException e) { return false; } catch (IOException e) { return false; } // if child index is -1, the drop was on top of the path, so we'll // treat it as inserting at the end of that path's list of children if (childIndex == -1) { childIndex = tree.getModel().getChildCount(path.getLastPathComponent()); } // create a new node to represent the data and insert it into the model DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(data); DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode) path.getLastPathComponent(); treeModel.insertNodeInto(newNode, parentNode, childIndex); // make the new node visible and scroll so that it's visible tree.makeVisible(path.pathByAddingChild(newNode)); tree.scrollRectToVisible(tree.getPathBounds(path.pathByAddingChild(newNode))); // demo stuff - remove for blog model.removeAllElements(); model.insertElementAt("String " + (++count), 0); // end demo stuff return true; } }); JList dragFrom = new JList(model); dragFrom.setFocusable(false); dragFrom.setPrototypeCellValue("String 0123456789"); model.insertElementAt("String " + count, 0); dragFrom.setDragEnabled(true); dragFrom.setBorder(BorderFactory.createLoweredBevelBorder()); JPanel p = new JPanel(); p.setLayout(new BoxLayout(p, BoxLayout.X_AXIS)); JPanel wrap = new JPanel(); wrap.add(new JLabel("Drag from here:")); wrap.add(dragFrom); p.add(Box.createHorizontalStrut(4)); p.add(Box.createGlue()); p.add(wrap); p.add(Box.createGlue()); p.add(Box.createHorizontalStrut(4)); getContentPane().add(p, BorderLayout.NORTH); getContentPane().add(new JScrollPane(tree), BorderLayout.CENTER); indicateCombo = new JComboBox(new String[] { "Default", "Always", "Never" }); indicateCombo.setSelectedItem("INSERT"); p = new JPanel(); p.setLayout(new BoxLayout(p, BoxLayout.X_AXIS)); wrap = new JPanel(); wrap.add(new JLabel("Show drop location:")); wrap.add(indicateCombo); p.add(Box.createHorizontalStrut(4)); p.add(Box.createGlue()); p.add(wrap); p.add(Box.createGlue()); p.add(Box.createHorizontalStrut(4)); getContentPane().add(p, BorderLayout.SOUTH); getContentPane().setPreferredSize(new Dimension(400, 450)); }
From source file:com.mirth.connect.client.ui.components.MirthTreeTable.java
public void setMirthTransferHandlerEnabled(boolean enable) { setDragEnabled(enable);/*from ww w . j a va 2s .c o m*/ if (transferHandler == null) { transferHandler = new TransferHandler() { @Override public int getSourceActions(JComponent c) { return COPY_OR_MOVE; } @Override protected Transferable createTransferable(JComponent c) { int row = getSelectedRow(); List columnValuesList = new ArrayList<Object>(); for (TableColumn column : getColumns()) { Object value = getValueAt(row, convertColumnIndexToView(column.getModelIndex())); if (value != null) { if (value instanceof Calendar) { Calendar calendar = (GregorianCalendar) value; SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT); dateFormat.setCalendar(calendar); value = (String) dateFormat.format(calendar.getTime()); } else if (value instanceof Long) { value = String.valueOf(value); } else if (value instanceof Status) { value = Status.fromChar(((Status) value).getStatusCode()); } else { value = String.valueOf(value); } } else { value = "-"; } columnValuesList.add(value); } return new StringSelection(StringUtils.join(columnValuesList, " ")); } }; setTransferHandler(transferHandler); } }
From source file:com.mirth.connect.connectors.ws.WebServiceSender.java
private void setAttachments(List<List<String>> attachments) { List<String> attachmentIds = attachments.get(0); List<String> attachmentContents = attachments.get(1); List<String> attachmentTypes = attachments.get(2); Object[][] tableData = new Object[attachmentIds.size()][3]; attachmentsTable = new MirthTable(); for (int i = 0; i < attachmentIds.size(); i++) { tableData[i][ID_COLUMN_NUMBER] = attachmentIds.get(i); tableData[i][CONTENT_COLUMN_NUMBER] = attachmentContents.get(i); tableData[i][MIME_TYPE_COLUMN_NUMBER] = attachmentTypes.get(i); }/*from w ww.j a v a 2s. c om*/ attachmentsTable.setModel(new javax.swing.table.DefaultTableModel(tableData, new String[] { ID_COLUMN_NAME, CONTENT_COLUMN_NAME, MIME_TYPE_COLUMN_NAME }) { boolean[] canEdit = new boolean[] { true, true, true }; public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit[columnIndex]; } }); attachmentsTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent evt) { if (attachmentsTable.getSelectedModelIndex() != -1) { deleteButton.setEnabled(true); } else { deleteButton.setEnabled(false); } } }); class AttachmentsTableCellEditor extends TextFieldCellEditor { boolean checkUnique; public AttachmentsTableCellEditor(boolean checkUnique) { super(); this.checkUnique = checkUnique; } public boolean checkUnique(String value) { boolean exists = false; for (int i = 0; i < attachmentsTable.getModel().getRowCount(); i++) { if (((String) attachmentsTable.getModel().getValueAt(i, ID_COLUMN_NUMBER)) .equalsIgnoreCase(value)) { exists = true; } } return exists; } @Override public boolean isCellEditable(EventObject evt) { boolean editable = super.isCellEditable(evt); if (editable) { deleteButton.setEnabled(false); } return editable; } @Override protected boolean valueChanged(String value) { deleteButton.setEnabled(true); if (checkUnique && (value.length() == 0 || checkUnique(value))) { return false; } parent.setSaveEnabled(true); return true; } } attachmentsTable.getColumnModel().getColumn(attachmentsTable.getColumnModelIndex(ID_COLUMN_NAME)) .setCellEditor(new AttachmentsTableCellEditor(true)); attachmentsTable.getColumnModel().getColumn(attachmentsTable.getColumnModelIndex(CONTENT_COLUMN_NAME)) .setCellEditor(new AttachmentsTableCellEditor(false)); attachmentsTable.getColumnModel().getColumn(attachmentsTable.getColumnModelIndex(MIME_TYPE_COLUMN_NAME)) .setCellEditor(new AttachmentsTableCellEditor(false)); attachmentsTable.setCustomEditorControls(true); attachmentsTable.setSelectionMode(0); attachmentsTable.setRowSelectionAllowed(true); attachmentsTable.setRowHeight(UIConstants.ROW_HEIGHT); attachmentsTable.setDragEnabled(true); attachmentsTable.setTransferHandler(new TransferHandler() { protected Transferable createTransferable(JComponent c) { try { MirthTable table = ((MirthTable) (c)); if (table == null) { return null; } int currRow = table.convertRowIndexToModel(table.getSelectedRow()); String text = ""; if (currRow >= 0 && currRow < table.getModel().getRowCount()) { text = (String) table.getModel().getValueAt(currRow, ID_COLUMN_NUMBER); } text = "<inc:Include href=\"cid:" + text + "\" xmlns:inc=\"http://www.w3.org/2004/08/xop/include\"/>"; return new StringSelection(text); } catch (ClassCastException cce) { return null; } } public int getSourceActions(JComponent c) { return COPY; } public boolean canImport(JComponent c, DataFlavor[] df) { return false; } }); attachmentsTable.setOpaque(true); attachmentsTable.setSortable(true); if (Preferences.userNodeForPackage(Mirth.class).getBoolean("highlightRows", true)) { Highlighter highlighter = HighlighterFactory.createAlternateStriping(UIConstants.HIGHLIGHTER_COLOR, UIConstants.BACKGROUND_COLOR); attachmentsTable.setHighlighters(highlighter); } attachmentsPane.setViewportView(attachmentsTable); deleteButton.setEnabled(false); }
From source file:ru.apertum.qsystem.client.forms.FAdmin.java
/** * Creates new form FAdmin/* w w w . jav a 2 s. co m*/ */ public FAdmin() { addWindowListener(new WindowListener() { @Override public void windowOpened(WindowEvent e) { } @Override public void windowClosing(WindowEvent e) { timer.stop(); } @Override public void windowClosed(WindowEvent e) { } @Override public void windowIconified(WindowEvent e) { } @Override public void windowDeiconified(WindowEvent e) { } @Override public void windowActivated(WindowEvent e) { Uses.closeSplash(); } @Override public void windowDeactivated(WindowEvent e) { } }); initComponents(); setTitle(getTitle() + " " + Uses.getLocaleMessage("project.name" + FAbout.getCMRC_SUFF())); try { setIconImage( ImageIO.read(FAdmin.class.getResource("/ru/apertum/qsystem/client/forms/resources/admin.png"))); } catch (IOException ex) { System.err.println(ex); } // final Toolkit kit = Toolkit.getDefaultToolkit(); setLocation((Math.round(kit.getScreenSize().width - getWidth()) / 2), (Math.round(kit.getScreenSize().height - getHeight()) / 2)); // ? ? final JFrame fr = this; tray = QTray.getInstance(fr, "/ru/apertum/qsystem/client/forms/resources/admin.png", getLocaleMessage("tray.caption")); tray.addItem(getLocaleMessage("tray.caption"), (ActionEvent e) -> { setVisible(true); setState(JFrame.NORMAL); }); tray.addItem("-", (ActionEvent e) -> { }); tray.addItem(getLocaleMessage("tray.exit"), (ActionEvent e) -> { dispose(); System.exit(0); }); int ii = 1; final ButtonGroup bg = new ButtonGroup(); final String currLng = Locales.getInstance().getLangCurrName(); for (String lng : Locales.getInstance().getAvailableLocales()) { final JRadioButtonMenuItem item = new JRadioButtonMenuItem( org.jdesktop.application.Application.getInstance(ru.apertum.qsystem.QSystem.class).getContext() .getActionMap(FAdmin.class, fr).get("setCurrentLang")); bg.add(item); item.setSelected(lng.equals(currLng)); item.setText(lng); // NOI18N item.setName("QRadioButtonMenuItem" + (ii++)); // NOI18N menuLangs.add(item); } // ?? ??. listUsers.addListSelectionListener((ListSelectionEvent e) -> { userListChange(); }); // ?? ??. listResponse.addListSelectionListener((ListSelectionEvent e) -> { responseListChange(); }); listSchedule.addListSelectionListener((ListSelectionEvent e) -> { scheduleListChange(); }); listCalendar.addListSelectionListener(new ListSelectionListener() { private int oldSelectedValue = 0; private int tmp = 0; public int getOldSelectedValue() { return oldSelectedValue; } public void setOldSelectedValue(int oldSelectedValue) { this.oldSelectedValue = tmp; this.tmp = oldSelectedValue; } private boolean canceled = false; @Override public void valueChanged(ListSelectionEvent e) { if (canceled) { canceled = false; } else { if (tableCalendar.getModel() instanceof CalendarTableModel) { final CalendarTableModel model = (CalendarTableModel) tableCalendar.getModel(); if (!model.isSaved()) { final int res = JOptionPane.showConfirmDialog(null, getLocaleMessage("calendar.change.title"), getLocaleMessage("calendar.change.caption"), JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE); switch (res) { case 0: // ? ?? model.save(); calendarListChange(); setOldSelectedValue(listCalendar.getSelectedIndex()); break; case 1: // ?? ?? calendarListChange(); setOldSelectedValue(listCalendar.getSelectedIndex()); break; case 2: // ?? ??? canceled = true; listCalendar.setSelectedIndex(getOldSelectedValue()); break; } } else { calendarListChange(); setOldSelectedValue(listCalendar.getSelectedIndex()); } } else { calendarListChange(); setOldSelectedValue(listCalendar.getSelectedIndex()); } } } }); // ?? ? ??. treeServices.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); treeInfo.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); /* treeServices.setCellRenderer(new DefaultTreeCellRenderer() { @Override public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) { super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus); setText(((Element) value).attributeValue(Uses.TAG_NAME)); return this; } });*/ treeServices.addTreeSelectionListener((TreeSelectionEvent e) -> { serviceListChange(); }); treeInfo.addTreeSelectionListener((TreeSelectionEvent e) -> { infoListChange(); }); textFieldStartTime.setInputVerifier(DateVerifier); textFieldFinishTime.setInputVerifier(DateVerifier); // ? loadSettings(); // ? ?. startTimer(); // loadConfig(); spinnerPropServerPort.getModel().addChangeListener(new ChangeNet()); spinnerPropClientPort.getModel().addChangeListener(new ChangeNet()); spinnerWebServerPort.getModel().addChangeListener(new ChangeNet()); spinnerServerPort.getModel().addChangeListener(new ChangeSettings()); spinnerClientPort.getModel().addChangeListener(new ChangeSettings()); spinnerUserRS.getModel().addChangeListener(new ChangeUser()); //? . final Helper helper = Helper.getHelp("ru/apertum/qsystem/client/help/admin.hs"); helper.setHelpListener(menuItemHelp); helper.enableHelpKey(jPanel1, "introduction"); helper.enableHelpKey(jPanel3, "monitoring"); helper.enableHelpKey(jPanel4, "configuring"); helper.enableHelpKey(jPanel8, "net"); helper.enableHelpKey(jPanel17, "schedulers"); helper.enableHelpKey(jPanel19, "calendars"); helper.enableHelpKey(jPanel2, "infoSystem"); helper.enableHelpKey(jPanel13, "responses"); helper.enableHelpKey(jPanel18, "results"); treeServices.setTransferHandler(new TransferHandler() { @Override public boolean canImport(TransferHandler.TransferSupport info) { final JTree.DropLocation dl = (JTree.DropLocation) info.getDropLocation(); if (dl.getChildIndex() == -1) { return false; } // Get the string that is being dropped. final Transferable t = info.getTransferable(); final QService data; try { data = (QService) t.getTransferData(DataFlavor.stringFlavor); return (data.getParent().getId() .equals(((QService) dl.getPath().getLastPathComponent()).getId())); } catch (UnsupportedFlavorException | IOException e) { return false; } } @Override public boolean importData(TransferHandler.TransferSupport info) { if (!info.isDrop()) { return false; } final QService data; try { data = (QService) info.getTransferable().getTransferData(DataFlavor.stringFlavor); } catch (UnsupportedFlavorException | IOException e) { System.err.println(e); return false; } final JTree.DropLocation dl = (JTree.DropLocation) info.getDropLocation(); final TreePath tp = dl.getPath(); final QService parent = (QService) tp.getLastPathComponent(); ((QServiceTree) treeServices.getModel()).moveNode(data, parent, dl.getChildIndex()); return true; } @Override public int getSourceActions(JComponent c) { return MOVE; } @Override protected Transferable createTransferable(JComponent c) { return (QService) ((JTree) c).getLastSelectedPathComponent(); } }); treeServices.setDropMode(DropMode.INSERT); // ? final AnnotationSessionFactoryBean as = (AnnotationSessionFactoryBean) Spring.getInstance().getFactory() .getBean("conf"); if (as.getServers().size() > 1) { final JMenu menu = new JMenu(getLocaleMessage("admin.servers")); as.getServers().stream().map((ser) -> { final JMenuItem mi1 = new JMenuItem(as); mi1.setText(ser.isCurrent() ? "<html><u><i>" + ser.getName() + "</i></u>" : ser.getName()); return mi1; }).forEach((mi1) -> { menu.add(mi1); }); jMenuBar1.add(menu, 4); jMenuBar1.add(new JLabel( "<html><span style='font-size:13.0pt;color:red'> [" + as.getName() + "]")); } comboBoxVoices.setVisible(false); }
From source file:org.apache.pdfbox.debugger.PDFDebugger.java
/** * This method is called from within the constructor to initialize the form. *///w w w. j a v a2 s. co m private void initComponents() { jSplitPane1 = new javax.swing.JSplitPane(); jScrollPane1 = new JScrollPane(); tree = new Tree(this); jScrollPane2 = new JScrollPane(); jTextPane1 = new javax.swing.JTextPane(); tree.setCellRenderer(new PDFTreeCellRenderer()); tree.setModel(null); setTitle("Apache PDFBox Debugger"); addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowOpened(WindowEvent windowEvent) { tree.requestFocusInWindow(); super.windowOpened(windowEvent); } @Override public void windowClosing(WindowEvent evt) { exitForm(evt); } }); jScrollPane1.setBorder(new BevelBorder(BevelBorder.RAISED)); jScrollPane1.setPreferredSize(new Dimension(350, 500)); tree.addTreeSelectionListener(new TreeSelectionListener() { @Override public void valueChanged(TreeSelectionEvent evt) { jTree1ValueChanged(evt); } }); jScrollPane1.setViewportView(tree); jSplitPane1.setRightComponent(jScrollPane2); jSplitPane1.setDividerSize(3); jScrollPane2.setPreferredSize(new Dimension(300, 500)); jScrollPane2.setViewportView(jTextPane1); jSplitPane1.setLeftComponent(jScrollPane1); JScrollPane documentScroller = new JScrollPane(); documentScroller.setViewportView(documentPanel); statusPane = new TreeStatusPane(tree); statusPane.getPanel().setBorder(new BevelBorder(BevelBorder.RAISED)); statusPane.getPanel().setPreferredSize(new Dimension(300, 25)); getContentPane().add(statusPane.getPanel(), BorderLayout.PAGE_START); getContentPane().add(jSplitPane1, BorderLayout.CENTER); statusBar = new ReaderBottomPanel(); getContentPane().add(statusBar, BorderLayout.SOUTH); // create menus JMenuBar menuBar = new JMenuBar(); menuBar.add(createFileMenu()); menuBar.add(createEditMenu()); menuBar.add(createViewMenu()); setJMenuBar(menuBar); Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); int width = 1000; int height = 970; setBounds((screenSize.width - width) / 2, (screenSize.height - height) / 2, width, height); // drag and drop to open files setTransferHandler(new TransferHandler() { @Override public boolean canImport(TransferSupport transferSupport) { return transferSupport.isDataFlavorSupported(DataFlavor.javaFileListFlavor); } @Override @SuppressWarnings("unchecked") public boolean importData(TransferSupport transferSupport) { try { Transferable transferable = transferSupport.getTransferable(); List<File> files = (List<File>) transferable.getTransferData(DataFlavor.javaFileListFlavor); readPDFFile(files.get(0), ""); return true; } catch (IOException e) { new ErrorDialog(e).setVisible(true); return true; } catch (UnsupportedFlavorException e) { throw new RuntimeException(e); } } }); // Mac OS X file open/quit handler if (IS_MAC_OS) { try { Method osxOpenFiles = getClass().getDeclaredMethod("osxOpenFiles", String.class); osxOpenFiles.setAccessible(true); OSXAdapter.setFileHandler(this, osxOpenFiles); Method osxQuit = getClass().getDeclaredMethod("osxQuit"); osxQuit.setAccessible(true); OSXAdapter.setQuitHandler(this, osxQuit); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } } }
From source file:org.gtdfree.GTDFree.java
protected TrayIcon getTrayIcon() { if (trayIcon == null) { if (ApplicationHelper.isGTKLaF()) { trayIcon = new TrayIcon(ApplicationHelper.loadImage(ApplicationHelper.icon_name_large_tray_splash)); } else {// w ww . j a v a2s.c om trayIcon = new TrayIcon(ApplicationHelper.loadImage(ApplicationHelper.icon_name_small_tray_splash)); } trayIcon.setImageAutoSize(true); trayIcon.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (e.getButton() == MouseEvent.BUTTON1) { trayIconPopup.setVisible(false); if (getJFrame().isVisible()) { getJFrame().setVisible(false); } else { pushVisible(); } } else { if (trayIconPopup.isVisible()) { trayIconPopup.setVisible(false); } else { Point p = new Point(e.getPoint()); /* * Disabled, because we are anyway doing things like rollover, * which are probably done by Frame. if (getJFrame().isShowing()) { SwingUtilities.convertPointFromScreen(p, getJFrame()); trayIconPopup.show(getJFrame(), p.x, p.y); } else { }*/ trayIconPopup.show(null, p.x, p.y); } } } }); trayIcon.setToolTip("GTD-Free - " + Messages.getString("GTDFree.Tray.desc")); //$NON-NLS-1$ //$NON-NLS-2$ /* * Necessary only when popup is showing with null window. Hides popup. */ MouseListener hideMe = new MouseAdapter() { @Override public void mouseExited(MouseEvent e) { if (e.getComponent() instanceof JMenuItem) { JMenuItem jm = (JMenuItem) e.getComponent(); jm.getModel().setRollover(false); jm.getModel().setArmed(false); jm.repaint(); } Point p = SwingUtilities.convertPoint(e.getComponent(), e.getPoint(), trayIconPopup); //System.out.println(p.x+" "+p.y+" "+trayIconPopup.getWidth()+" "+trayIconPopup.getHeight()); if (p.x < 0 || p.x >= trayIconPopup.getWidth() || p.y < 0 || p.y >= trayIconPopup.getHeight()) { trayIconPopup.setVisible(false); } } @Override public void mouseEntered(MouseEvent e) { if (e.getComponent() instanceof JMenuItem) { JMenuItem jm = (JMenuItem) e.getComponent(); jm.getModel().setRollover(true); jm.getModel().setArmed(true); jm.repaint(); } } }; trayIconPopup = new JPopupMenu(); trayIconPopup.addMouseListener(hideMe); JMenuItem mi = new JMenuItem(Messages.getString("GTDFree.Tray.Drop")); //$NON-NLS-1$ mi.setIcon(ApplicationHelper.getIcon(ApplicationHelper.icon_name_small_collecting)); mi.setToolTipText(Messages.getString("GTDFree.Tray.Drop.desc")); //$NON-NLS-1$ mi.addMouseListener(hideMe); /* * Workaround for tray, if JFrame is showing, then mouse click is not fired */ mi.addMouseListener(new MouseAdapter() { private boolean click = false; @Override public void mousePressed(MouseEvent e) { click = true; } @Override public void mouseReleased(MouseEvent e) { if (click) { click = false; doMouseClicked(e); } } @Override public void mouseExited(MouseEvent e) { click = false; } private void doMouseClicked(MouseEvent e) { trayIconPopup.setVisible(false); Clipboard c = null; if (e.getButton() == MouseEvent.BUTTON1) { c = Toolkit.getDefaultToolkit().getSystemClipboard(); } else if (e.getButton() == MouseEvent.BUTTON2) { c = Toolkit.getDefaultToolkit().getSystemSelection(); } else { return; } try { Object o = c.getData(DataFlavor.stringFlavor); if (o != null) { getEngine().getGTDModel().collectAction(o.toString()); } flashMessage(Messages.getString("GTDFree.Tray.Collect.ok"), e.getLocationOnScreen()); //$NON-NLS-1$ } catch (Exception e1) { Logger.getLogger(this.getClass()).debug("Internal error.", e1); //$NON-NLS-1$ flashMessage(Messages.getString("GTDFree.Tray.Collect.fail") + e1.getMessage(), //$NON-NLS-1$ e.getLocationOnScreen()); } } }); TransferHandler th = new TransferHandler() { private static final long serialVersionUID = 1L; @Override public boolean canImport(JComponent comp, DataFlavor[] transferFlavors) { return DataFlavor.selectBestTextFlavor(transferFlavors) != null; } @Override public boolean importData(JComponent comp, Transferable t) { try { DataFlavor f = DataFlavor.selectBestTextFlavor(t.getTransferDataFlavors()); Object o = t.getTransferData(f); if (o != null) { getEngine().getGTDModel().collectAction(o.toString()); } return true; } catch (UnsupportedFlavorException e) { Logger.getLogger(this.getClass()).debug("Internal error.", e); //$NON-NLS-1$ } catch (IOException e) { Logger.getLogger(this.getClass()).debug("Internal error.", e); //$NON-NLS-1$ } return false; } }; mi.setTransferHandler(th); trayIconPopup.add(mi); mi = new JMenuItem(); mi.setIcon(ApplicationHelper.getIcon(ApplicationHelper.icon_name_large_delete)); mi.setText(Messages.getString("GTDFree.Tray.Hide")); //$NON-NLS-1$ mi.setToolTipText(Messages.getString("GTDFree.Tray.Hide.desc")); //$NON-NLS-1$ mi.addMouseListener(hideMe); mi.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { trayIconPopup.setVisible(false); if (getJFrame().isVisible()) { getJFrame().setVisible(false); } } }); trayIconPopup.add(mi); mi = new JMenuItem(); mi.setIcon(ApplicationHelper.getIcon(ApplicationHelper.icon_name_small_splash)); mi.setText(Messages.getString("GTDFree.Tray.Show")); //$NON-NLS-1$ mi.setToolTipText(Messages.getString("GTDFree.Tray.Show.desc")); //$NON-NLS-1$ mi.addMouseListener(hideMe); mi.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { trayIconPopup.setVisible(false); pushVisible(); } }); trayIconPopup.add(mi); mi = new JMenuItem(); mi.setIcon(ApplicationHelper.getIcon(ApplicationHelper.icon_name_large_exit)); mi.setText(Messages.getString("GTDFree.Tray.Exit")); //$NON-NLS-1$ mi.addMouseListener(hideMe); mi.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { trayIconPopup.setVisible(false); close(false); } }); trayIconPopup.add(mi); } return trayIcon; }
From source file:org.nuclos.client.genericobject.GenericObjectCollectController.java
private void prepareTableForDragAndDrop(final JTable tbl) { tbl.setDragEnabled(true);//from ww w . ja va2 s.c o m tbl.setTransferHandler(new TransferHandler() { @Override public int getSourceActions(JComponent comp) { int result = NONE; if (comp == tbl) if (GenericObjectCollectController.this.getSelectedCollectable() != null) result = COPY; return result; } @Override protected Transferable createTransferable(JComponent comp) { Transferable result = null; if (comp == tbl) { final int[] aiSelectedRows = tbl.getSelectedRows(); final List<GenericObjectIdModuleProcess> lstgoimp = new ArrayList<GenericObjectIdModuleProcess>( aiSelectedRows.length); for (int iSelectedRow : aiSelectedRows) { final CollectableGenericObjectWithDependants clct = getResultTableModel() .getCollectable(iSelectedRow); GenericObjectIdModuleProcess transferableObject = getTransferableObject(tbl, iSelectedRow, clct); lstgoimp.add(transferableObject); } if (!lstgoimp.isEmpty()) result = new TransferableGenericObjects(lstgoimp); } return result; } private GenericObjectIdModuleProcess getTransferableObject(final JTable tbl, int iSelectedRow, final CollectableGenericObjectWithDependants clct) { return new GenericObjectIdModuleProcess(clct, getTreeViewIdentifier(clct), getContents(tbl, iSelectedRow)); } private String getContents(JTable tbl, int iRow) { final StringBuffer sb = new StringBuffer(); final int iColumnCount = tbl.getColumnCount(); for (int iColumn = 0; iColumn < iColumnCount; iColumn++) { final String sValue = tbl.getValueAt(iRow, iColumn).toString(); if (sValue.indexOf("\n") >= 0 || sValue.indexOf("\t") >= 0) { sb.append("\""); sb.append(sValue.replaceAll("\"", "\"\"")); sb.append("\""); } else { sb.append(sValue); } if (iColumn < iColumnCount - 1) sb.append("\t"); } return sb.toString(); } }); }
From source file:org.rimudb.editor.DescriptorEditor.java
/** * Build the panel/*from w w w .java2 s . co m*/ */ private JPanel createColumnTablePanel() { JPanel columnPanel = new JPanel(); columnPanel.setLayout(new BoxLayout(columnPanel, BoxLayout.Y_AXIS)); // Create the property table panel propertyModel = new PropertyTableModel(); // Add a listener to set the changed state propertyModel.addTableModelListener(new TableModelListener() { public void tableChanged(TableModelEvent e) { markChanged(); if (e instanceof PropertyTableModelEvent) { PropertyTableModelEvent ptme = (PropertyTableModelEvent) e; // If the columnName column was changed then check it isn't // a PK if (ptme.getColumn() == 1) { String beforeColumnName = (String) ptme.getBeforeValue(); String afterColumnName = (String) ptme.getAfterValue(); // Is the field entry in the list of primary keys? for (int i = 0; i < pkListModel.getSize(); i++) { String pkColumnName = (String) pkListModel.get(i); // If it's found then remove it if (beforeColumnName.equals(pkColumnName)) { pkListModel.set(i, afterColumnName); break; } } } } } }); table = new ATable(getPropertyModel()); table.setName("ColumnTable"); table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); table.getSelectionModel().addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { int selectedRowCount = table.getSelectedRowCount(); removeColumnBtn.setEnabled(selectedRowCount > 0); moveUpBtn.setEnabled(selectedRowCount > 0); moveDownBtn.setEnabled(selectedRowCount > 0); } }); table.setTransferHandler(new TransferHandler() { public int getSourceActions(JComponent c) { return COPY; } protected Transferable createTransferable(JComponent c) { ATable columnTable = (ATable) c; int row = columnTable.getSelectedRow(); String columnName = getPropertyModel().getRow(row).getColumnName(); return new StringSelection(columnName); } }); table.setDragEnabled(true); JScrollPane sp = new JScrollPane(table); sp.setMaximumSize(new Dimension(Short.MAX_VALUE, 325)); sp.setPreferredSize(new Dimension(Short.MAX_VALUE, 325)); sp.setMinimumSize(new Dimension(Short.MAX_VALUE, 325)); JComboBox typeCB = new JComboBox(DatabaseTypes.getAllTypes()); typeCB.setEditable(false); javax.swing.table.TableColumn typeColumn = table.getColumnModel().getColumn(2); typeColumn.setCellEditor(new DefaultCellEditor(typeCB)); // Create the popup menu and set it on the table propertyPopup = new TablePopupMenu(this, table); table.addMouseListener(propertyPopup); sp.addMouseListener(propertyPopup); sp.setAlignmentX(LEFT_ALIGNMENT); columnPanel.add(sp); columnPanel.add(Box.createVerticalStrut(10)); JLabel pkLabel = new JLabel("Primary Key Columns", SwingConstants.LEFT); pkLabel.setAlignmentX(LEFT_ALIGNMENT); columnPanel.add(pkLabel); pkListModel = new DefaultListModel(); pkListModel.addListDataListener(new ListDataListener() { public void intervalRemoved(ListDataEvent e) { markChanged(); } public void intervalAdded(ListDataEvent e) { markChanged(); } public void contentsChanged(ListDataEvent e) { markChanged(); } }); pkList = new JList(pkListModel); pkList.setName("pkList"); pkList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); pkList.addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { int selectedRowCount = pkList.getSelectedIndex(); removePkBtn.setEnabled(selectedRowCount > -1); } }); pkList.setTransferHandler(new TransferHandler() { public boolean canImport(TransferHandler.TransferSupport info) { // we only import Strings if (!info.isDataFlavorSupported(DataFlavor.stringFlavor)) { return false; } JList.DropLocation dl = (JList.DropLocation) info.getDropLocation(); if (dl.getIndex() == -1) { return false; } return true; } public boolean importData(TransferHandler.TransferSupport info) { if (!info.isDrop()) { return false; } // Check for String flavor if (!info.isDataFlavorSupported(DataFlavor.stringFlavor)) { displayDropLocation("List doesn't accept a drop of this type."); return false; } JList.DropLocation dl = (JList.DropLocation) info.getDropLocation(); DefaultListModel listModel = (DefaultListModel) pkList.getModel(); int index = dl.getIndex(); // Get the string that is being dropped. Transferable t = info.getTransferable(); String data; try { data = (String) t.getTransferData(DataFlavor.stringFlavor); } catch (Exception e) { return false; } // If this is a copy action then check we don't already have that String if (info.getDropAction() == COPY && listModel.indexOf(data) > -1) { displayDropLocation("The column " + data + " is already a primary key"); return false; } // Perform the actual import. if (dl.isInsert()) { int oldIndex = listModel.indexOf(data); if (oldIndex < index) { listModel.add(index, data); listModel.remove(oldIndex); } else { listModel.remove(oldIndex); listModel.add(index, data); } } else { // Don't handle replacements } return true; } public int getSourceActions(JComponent c) { return MOVE; } protected Transferable createTransferable(JComponent c) { JList list = (JList) c; Object[] values = list.getSelectedValues(); StringBuffer buff = new StringBuffer(); for (int i = 0; i < values.length; i++) { Object val = values[i]; buff.append(val == null ? "" : val.toString()); if (i != values.length - 1) { buff.append("\n"); } } return new StringSelection(buff.toString()); } }); pkList.setDropMode(DropMode.INSERT); pkList.setDragEnabled(true); JScrollPane pkScrollPanel = new JScrollPane(pkList); pkScrollPanel.setMaximumSize(new Dimension(Short.MAX_VALUE, 100)); pkScrollPanel.setAlignmentX(LEFT_ALIGNMENT); columnPanel.add(pkScrollPanel); return columnPanel; }
From source file:org.simmi.GeneSetHead.java
License:asdf
public TransferHandler dragRows(final JTable table, final List<String> specs) { TransferHandler th = null;//from w ww .j a v a 2 s . co m try { final DataFlavor ndf = new DataFlavor(DataFlavor.javaJVMLocalObjectMimeType); final DataFlavor df = DataFlavor.getTextPlainUnicodeFlavor(); final String charset = df.getParameter("charset"); final Transferable transferable = new Transferable() { @Override public Object getTransferData(DataFlavor arg0) throws UnsupportedFlavorException, IOException { if (arg0.equals(ndf)) { int[] rr = currentRowSelection; //table.getSelectedRows(); List<String> selseq = new ArrayList<String>(rr.length); for (int r : rr) { int i = table.convertRowIndexToModel(r); selseq.add(specs.get(i)); } return selseq; } else { String ret = "";//makeCopyString(); for (int r = 0; r < table.getRowCount(); r++) { Object o = table.getValueAt(r, 0); if (o != null) { ret += o.toString(); } else { ret += ""; } for (int c = 1; c < table.getColumnCount(); c++) { o = table.getValueAt(r, c); if (o != null) { ret += "\t" + o.toString(); } else { ret += "\t"; } } ret += "\n"; } //return arg0.getReaderForText( this ); return new ByteArrayInputStream(ret.getBytes(charset)); } //return ret; } @Override public DataFlavor[] getTransferDataFlavors() { return new DataFlavor[] { df, ndf }; } @Override public boolean isDataFlavorSupported(DataFlavor arg0) { if (arg0.equals(df) || arg0.equals(ndf)) { return true; } return false; } }; th = new TransferHandler() { private static final long serialVersionUID = 1L; public int getSourceActions(JComponent c) { return TransferHandler.COPY_OR_MOVE; } public boolean canImport(TransferHandler.TransferSupport support) { return true; } protected Transferable createTransferable(JComponent c) { currentRowSelection = table.getSelectedRows(); return transferable; } public boolean importData(TransferHandler.TransferSupport support) { try { System.err.println(table.getSelectedRows().length); DataFlavor[] dfs = support.getDataFlavors(); if (support.isDataFlavorSupported(ndf)) { Object obj = support.getTransferable().getTransferData(ndf); ArrayList<String> seqs = (ArrayList<String>) obj; /*ArrayList<String> newlist = new ArrayList<String>( serifier.lgse.size() ); for( int r = 0; r < table.getRowCount(); r++ ) { int i = table.convertRowIndexToModel(r); newlist.add( specs.get(i) ); } serifier.lgseq.clear(); serifier.lgseq = newlist;*/ Point p = support.getDropLocation().getDropPoint(); int k = table.rowAtPoint(p); specs.removeAll(seqs); for (String s : seqs) { specs.add(k++, s); } TableRowSorter<TableModel> trs = (TableRowSorter<TableModel>) table.getRowSorter(); trs.setSortKeys(null); table.tableChanged(new TableModelEvent(table.getModel())); return true; } /* else if( support.isDataFlavorSupported( df ) ) { Object obj = support.getTransferable().getTransferData( df ); InputStream is = (InputStream)obj; System.err.println( charset ); importReader( new BufferedReader(new InputStreamReader(is, charset)) ); updateView(); return true; } else if( support.isDataFlavorSupported( DataFlavor.stringFlavor ) ) { Object obj = support.getTransferable().getTransferData( DataFlavor.stringFlavor ); String str = (String)obj; importReader( new BufferedReader( new StringReader(str) ) ); updateView(); return true; }*/ } catch (UnsupportedFlavorException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return false; } }; } catch (Exception e) { e.printStackTrace(); } return th; }