List of usage examples for javax.swing JList getModel
public ListModel<E> getModel()
JList
component. From source file:edu.ku.brc.specify.tasks.subpane.wb.DataImportDialog.java
/** * Takes the list of data import errors and displays then to the user * * void//from www . j a v a 2 s . c om */ protected void showErrors() { JList listOfErrors = genListOfErrorWhereTableDataDefiesSizeConstraints(model.getColumnNames(), model.getData()); if ((model.getColumnNames() == null) || (model.getData() == null) || (listOfErrors == null) || (listOfErrors.getModel().getSize() == 0)) { JTextArea textArea = new JTextArea(); textArea.setRows(25); textArea.setColumns(60); //String newline = "\n"; //for (int i = 0; i < listOfErrors.getModel().getSize(); i++) //{ textArea.append(getResourceString("WB_PARSE_FILE_ERROR2")); //} textArea.setLineWrap(true); textArea.setWrapStyleWord(true); textArea.setEditable(false); textArea.setCaretPosition(0); JScrollPane pane = new JScrollPane(textArea, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS); JOptionPane.showMessageDialog(UIRegistry.getTopWindow(), pane, getResourceString("DATA_IMPORT_ISSUES"), JOptionPane.WARNING_MESSAGE); okBtn.setEnabled(false); } else if (listOfErrors.getModel().getSize() > 0) { JTextArea textArea = new JTextArea(); textArea.setRows(25); textArea.setColumns(60); String newline = "\n"; for (int i = 0; i < listOfErrors.getModel().getSize(); i++) { textArea.append((String) listOfErrors.getModel().getElementAt(i) + newline + newline); } textArea.setLineWrap(true); textArea.setWrapStyleWord(true); textArea.setEditable(false); textArea.setCaretPosition(0); JScrollPane pane = new JScrollPane(textArea, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS); JOptionPane.showMessageDialog(UIRegistry.getTopWindow(), pane, getResourceString("DATA_IMPORT_ISSUES"), JOptionPane.WARNING_MESSAGE); } }
From source file:es.emergya.ui.plugins.admin.aux1.SummaryAction.java
private JPanel buildPanelFilter(final String topLabel, final int textfieldSize, final Dimension dimension, final JList list, final boolean left) { JPanel left_filtro = new JPanel(new GridBagLayout()); left_filtro.setPreferredSize(dimension); left_filtro.setOpaque(false);// ww w . j av a 2s . c o m final GridBagConstraints gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.gridy = 0; gbc.anchor = GridBagConstraints.BASELINE_LEADING; left_filtro.add(new JLabel(topLabel, JLabel.LEFT), gbc); final JTextField filtro = new JTextField(textfieldSize); gbc.gridy++; left_filtro.add(filtro, gbc); AbstractAction actionStartFilter = new AbstractAction(null, getIcon("Buttons.noFiltrar")) { private static final long serialVersionUID = -4737487889360372801L; @Override public void actionPerformed(ActionEvent e) { ((DefaultListModel) list.getModel()).removeAllElements(); filtro.setText(null); if (left) { for (Object obj : leftItems) { ((DefaultListModel) list.getModel()).addElement(obj); } } else { for (Object obj : rightItems) { ((DefaultListModel) list.getModel()).addElement(obj); } } } }; AbstractAction actionStopFilter = new AbstractAction(null, getIcon("Buttons.filtrar")) { private static final long serialVersionUID = 6570608476764008290L; @Override public void actionPerformed(ActionEvent e) { ((DefaultListModel) list.getModel()).removeAllElements(); if (left) { for (Object obj : leftItems) { if (compare(filtro, obj)) { ((DefaultListModel) list.getModel()).addElement(obj); } } } else { for (Object obj : rightItems) { if (compare(filtro, obj)) { ((DefaultListModel) list.getModel()).addElement(obj); } } } } private boolean compare(final JTextField filtro, Object obj) { final String elemento = obj.toString().toUpperCase().trim(); final String text = filtro.getText().toUpperCase().trim(); final String pattern = text.replace("*", ".*"); boolean res = Pattern.matches(pattern, elemento); return res;// || elemento.indexOf(text) >= 0; } }; JButton jButton = new JButton(actionStartFilter); JButton jButton2 = new JButton(actionStopFilter); jButton.setBorderPainted(false); jButton2.setBorderPainted(false); jButton.setContentAreaFilled(false); jButton2.setContentAreaFilled(false); jButton.setPreferredSize( new Dimension(jButton.getIcon().getIconWidth(), jButton.getIcon().getIconHeight())); jButton2.setPreferredSize( new Dimension(jButton2.getIcon().getIconWidth(), jButton2.getIcon().getIconHeight())); gbc.gridx++; left_filtro.add(jButton2, gbc); gbc.gridx++; left_filtro.add(jButton, gbc); return left_filtro; }
From source file:DragListDemo.java
public boolean importData(JComponent c, Transferable t) { JList target = null; ArrayList alist = null;//from ww w . j a va 2 s .com if (!canImport(c, t.getTransferDataFlavors())) { return false; } try { target = (JList) c; if (hasLocalArrayListFlavor(t.getTransferDataFlavors())) { alist = (ArrayList) t.getTransferData(localArrayListFlavor); } else if (hasSerialArrayListFlavor(t.getTransferDataFlavors())) { alist = (ArrayList) t.getTransferData(serialArrayListFlavor); } else { return false; } } catch (UnsupportedFlavorException ufe) { System.out.println("importData: unsupported data flavor"); return false; } catch (IOException ioe) { System.out.println("importData: I/O exception"); return false; } //At this point we use the same code to retrieve the data //locally or serially. //We'll drop at the current selected index. int index = target.getSelectedIndex(); //Prevent the user from dropping data back on itself. //For example, if the user is moving items #4,#5,#6 and #7 and //attempts to insert the items after item #5, this would //be problematic when removing the original items. //This is interpreted as dropping the same data on itself //and has no effect. if (source.equals(target)) { if (indices != null && index >= indices[0] - 1 && index <= indices[indices.length - 1]) { indices = null; return true; } } DefaultListModel listModel = (DefaultListModel) target.getModel(); int max = listModel.getSize(); if (index < 0) { index = max; } else { index++; if (index > max) { index = max; } } addIndex = index; addCount = alist.size(); for (int i = 0; i < alist.size(); i++) { listModel.add(index++, alist.get(i)); } return true; }
From source file:edu.ku.brc.specify.config.ResourceImportExportDlg.java
/** * Enables the Import / Export and Revert Buttons *///from w ww . j a v a2s . c om protected void enableUI() { int currentTabIndex = tabbedPane.getModel().getSelectedIndex(); if (currentTabIndex == 0) // Views { boolean enable = !viewSetsList.isSelectionEmpty(); importBtn.setEnabled(enable && levelCBX.getSelectedIndex() < 5); exportBtn.setEnabled(enable && viewSetsModel.size() > 0); if (viewSetsList.getSelectedValue() instanceof SpViewSetObj) { SpViewSetObj vso = (SpViewSetObj) viewSetsList.getSelectedValue(); revertBtn.setEnabled(vso != null && vso.getId() != null); } else { revertBtn.setEnabled(false); } } else if (currentTabIndex != -1) { JList activeList = tabbedPane.getSelectedComponent() == resPanel ? resList : repList; if (activeList.getSelectedValue() instanceof String) { importBtn.setEnabled(true); exportBtn.setEnabled(false); revertBtn.setEnabled(false); } else { boolean hasOthersTab = tabbedPane.getTabCount() > 2; boolean enable = !activeList.isSelectionEmpty(); int numItems = ((DefaultListModel) activeList.getModel()).size(); importBtn.setEnabled(enable && (levelCBX.getSelectedIndex() < 2 || (numItems > 1 && hasOthersTab))); exportBtn.setEnabled(enable && numItems > 1); SpAppResource appRes = (SpAppResource) activeList.getSelectedValue(); enable = false; if (appRes != null && appRes.getId() != null) { if (appRes.getMimeType() != null && (appRes.getMimeType().equals(ReportsBaseTask.REPORTS_MIME) || appRes.getMimeType().equals(ReportsBaseTask.LABELS_MIME))) { //if (!isSpReportResource((SpAppResource )appRes)) { //XXX what if appres is imported report with no config file??? enable = true; //revert not currently working } } else { enable = true; } } revertBtn.setEnabled(enable); } } }
From source file:com.vgi.mafscaling.LogView.java
private void createLogViewPanel() { logViewPanel = new JPanel(); GridBagLayout gbl_logViewPanel = new GridBagLayout(); gbl_logViewPanel.columnWidths = new int[] { 0 }; gbl_logViewPanel.rowHeights = new int[] { 0, 0 }; gbl_logViewPanel.columnWeights = new double[] { 1.0 }; gbl_logViewPanel.rowWeights = new double[] { 1.0, 0.0 }; logViewPanel.setLayout(gbl_logViewPanel); try {//from w w w . j a v a2 s .c om logDataTable = new DBTable(); logDataTable.copyColumnHeaderNames = true; logDataTable.defaultClickCountToStartEditor = 2; logDataTable.doNotUseDatabaseSort = true; logDataTable.listenKeyPressEventsWholeWindow = true; logDataTable.createControlPanel(DBTable.READ_NAVIGATION); logDataTable.enableExcelCopyPaste(); logDataTable.setSortEnabled(false); logDataTable.setSkin(new TableSkin()); logDataTable.refresh(new String[1][25]); logDataTable.setComparator(new DoubleComparator()); logDataTable.getTable().setCellSelectionEnabled(true); logDataTable.getTable().setColumnSelectionAllowed(true); logDataTable.getTable().setRowSelectionAllowed(true); logDataTable.getTable().setSelectionMode(ListSelectionModel.SINGLE_SELECTION); JTextField rowTextField = ((JTextField) logDataTable.getControlPanel().getComponent(3)); rowTextField.setPreferredSize(null); rowTextField.setColumns(5); GridBagConstraints gbc_logDataTable = new GridBagConstraints(); gbc_logDataTable.insets = insets0; gbc_logDataTable.anchor = GridBagConstraints.PAGE_START; gbc_logDataTable.fill = GridBagConstraints.BOTH; gbc_logDataTable.gridx = 0; gbc_logDataTable.gridy = 0; logViewPanel.add(logDataTable, gbc_logDataTable); listModel = new DefaultListModel<JLabel>(); selectionCombo.removeAllItems(); String name; JTableHeader tableHeader = logDataTable.getTableHeader(); for (int i = 0; i < logDataTable.getColumnCount(); ++i) { Column col = logDataTable.getColumn(i); col.setNullable(true); col.setHeaderRenderer(new CheckboxHeaderRenderer(i + 1, tableHeader)); name = col.getHeaderValue().toString(); selectionCombo.addItem(name); listModel.addElement(new JLabel(name, new CheckBoxIcon(), JLabel.LEFT)); } JList<JLabel> menuList = new JList<JLabel>(listModel); menuList.setOpaque(false); menuList.setCellRenderer(new ImageListCellRenderer()); menuList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); menuList.setLayoutOrientation(JList.VERTICAL); menuList.setFixedCellHeight(25); menuList.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { try { if (e.getClickCount() == 1 && colors.size() > 0) { JList<?> list = (JList<?>) e.getSource(); int index = list.locationToIndex(e.getPoint()); if (index >= 0) { int colIdx = logDataTable.getCurrentIndexForOriginalColumn(index); Column col = logDataTable.getColumn(colIdx); if (col.getHeaderRenderer() instanceof CheckboxHeaderRenderer) { CheckboxHeaderRenderer renderer = (CheckboxHeaderRenderer) col .getHeaderRenderer(); JLabel label = (JLabel) list.getModel().getElementAt(index); CheckBoxIcon checkIcon = (CheckBoxIcon) label.getIcon(); checkIcon.setChecked(!checkIcon.isChecked()); if (checkIcon.isChecked()) { checkIcon.setColor(colors.pop()); JTable table = logDataTable.getTable(); TableModel model = table.getModel(); addXYSeries(model, index, col.getHeaderValue().toString(), checkIcon.getColor()); } else { colors.push(checkIcon.getColor()); checkIcon.setColor(renderer.getDefaultColor()); removeXYSeries(index); } list.repaint(); } } } } catch (Exception ex) { ex.printStackTrace(); } } }); headerScrollPane = new JScrollPane(menuList); GridBagConstraints gbc_headersTree = new GridBagConstraints(); gbc_headersTree.insets = insets0; gbc_headersTree.anchor = GridBagConstraints.PAGE_START; gbc_headersTree.fill = GridBagConstraints.BOTH; gbc_headersTree.gridx = 0; gbc_headersTree.gridy = 1; logViewPanel.add(headerScrollPane, gbc_headersTree); headerScrollPane.setVisible(false); } catch (Exception e) { e.printStackTrace(); logger.error(e); } }
From source file:es.emergya.ui.plugins.admin.aux1.SummaryAction.java
private JList buildJList(final Dimension dimension, final Object[] items, final JList list, final boolean sort) { if (items == null) { return null; }/*from w w w .jav a 2s .c o m*/ list.setModel(new DefaultListModel() { @Override public void addElement(Object obj) { boolean inserted = false; if (sort) { for (int i = 0; i < this.getSize() && !inserted; i++) { try { final String comparator = ((obj == null) ? "" : obj.toString()); if (this.get(i).toString().compareTo(comparator) > 0) { this.add(i, obj); inserted = true; } } catch (Throwable t) { log.error("Error al ordenar a " + obj + " y no lo incluimos", t); inserted = true; } } } if (!inserted) { super.addElement(obj); } } }); log.trace("Lista con " + items.length + " objetos"); for (Object obj : items) { ((DefaultListModel) list.getModel()).addElement(obj); } list.setCellRenderer(new DefaultListCellRenderer() { private static final long serialVersionUID = -987995602141400182L; @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { JLabel c = new JLabel(); c.setText(value.toString()); if (isSelected) { c.setOpaque(true); c.setBackground(Color.YELLOW); } return c; } }); list.setMinimumSize(dimension); list.setFixedCellHeight(22); return list; }
From source file:de.innovationgate.utils.WGUtils.java
/** * Sets the selected items on a {@link JList}, which is a tedious task to do by hand. * @param selection The items that should be selected in the list * @param list The list itself/*from www .ja v a 2 s . c om*/ */ @SuppressWarnings({ "rawtypes", "unchecked" }) public static void setJListSelection(List selection, JList list) { // Load JList model data in array list List modelItems = new ArrayList(); ListModel listModel = list.getModel(); for (int i = 0; i < listModel.getSize(); i++) { modelItems.add(listModel.getElementAt(i)); } // Determine indices of selection items List indices = new ArrayList(); Iterator items = selection.iterator(); while (items.hasNext()) { Object item = items.next(); int index = modelItems.indexOf(item); if (index != -1) { indices.add(new Integer(index)); } } // Convert Integer list to int array (man, this is awkward...) int[] indicesArr = new int[indices.size()]; for (int i = 0; i < indices.size(); i++) { indicesArr[i] = ((Integer) indices.get(i)).intValue(); } // Set selection list.setSelectedIndices(indicesArr); }
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);/* w w w . j av a2 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:dnd.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 va 2s .co 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:edu.ku.brc.specify.utilapps.RegisterApp.java
/** * //from w w w . j av a2 s. c o m */ @SuppressWarnings("unchecked") protected void doSetVersion() { CellConstraints cc = new CellConstraints(); PanelBuilder pb = new PanelBuilder(new FormLayout("f:p:g", "p,2px,f:p:g")); Vector<String> versionsList = new Vector<String>(); Hashtable<String, String> verToDateHash = new Hashtable<String, String>(); try { SimpleDateFormat mmddyyyy = new SimpleDateFormat("MM/dd/yyyy"); SimpleDateFormat yyyymmdd = new SimpleDateFormat("yyyy/MM/dd"); List<String> lines = FileUtils.readLines(rp.getDataFromWeb( UIRegistry.getResourceString("CGI_BASE_URL") + "/specifydownloads/specify6/alpha/versions.txt", false)); for (String line : lines) { String[] toks = line.split(","); if (toks.length > 2) { String ver = StringUtils.remove(toks[1].trim(), "Alpha "); versionsList.insertElementAt(ver, 0); String dateStr = toks[2].trim(); dateStr = StringUtils.replace(dateStr, ".", "/"); try { Date date = mmddyyyy.parse(dateStr); verToDateHash.put(ver, yyyymmdd.format(date)); } catch (Exception ex) { } } } versionsList.insertElementAt("Clear", 0); } catch (IOException ex) { ex.printStackTrace(); } final JList list = new JList(versionsList); final CustomDialog dlg = new CustomDialog(null, "Set Version", true, pb.getPanel()); pb.add(UIHelper.createLabel("Versions", SwingConstants.CENTER), cc.xy(1, 1)); pb.add(UIHelper.createScrollPane(list), cc.xy(1, 3)); list.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { if (!e.getValueIsAdjusting()) { dlg.getOkBtn().setEnabled(list.getSelectedIndex() > -1); } } }); list.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { super.mouseClicked(e); if (e.getClickCount() == 2) { dlg.getOkBtn().doClick(); } } }); pb.setDefaultDialogBorder(); dlg.createUI(); dlg.getOkBtn().setEnabled(false); dlg.setVisible(true); if (!dlg.isCancelled()) { int inx = list.getSelectedIndex(); String version = (String) list.getSelectedValue(); if (version.equals("Clear")) { rp.setVersionDates(null, null, null); frame.setTitle(title); } else { String prevVersion = inx == list.getModel().getSize() - 1 ? null : (String) list.getModel().getElementAt(inx + 1); rp.setVersionDates(version, prevVersion, verToDateHash); frame.setTitle(title + " for " + version); } /*try { rp.process(doLocal ? new File("reg.dat") : rp.getDataFromWeb("SpReg.REGISTER_URL", true)); rp.processTracks(doLocal ? new File("track.dat") : rp.getDataFromWeb("StatsTrackerTask.URL", true)); rp.mergeStats(); } catch (IOException ex) { ex.printStackTrace(); }*/ } }