List of usage examples for javax.swing JList getSelectionModel
public ListSelectionModel getSelectionModel()
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 ww . j a v 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 va2 s . com*/ 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.conversion.ConvertVerifier.java
/** * @return// ww w . j a va 2 s. c o m * @throws SQLException */ private Pair<String, String> chooseTable() throws SQLException { MySQLDMBSUserMgr mgr = new MySQLDMBSUserMgr(); final Vector<DBNamePair> availOldPairs = new Vector<DBNamePair>(); final Vector<DBNamePair> availNewPairs = new Vector<DBNamePair>(); try { if (mgr.connectToDBMS(itUsrPwd.first, itUsrPwd.second, hostName)) { BasicSQLUtils.setSkipTrackExceptions(true); Connection conn = mgr.getConnection(); Vector<Object[]> dbNames = BasicSQLUtils.query(conn, "show databases"); for (Object[] row : dbNames) { System.err.println("Setting [" + row[0].toString() + "] "); conn.setCatalog(row[0].toString()); boolean isSp5 = false; boolean isSp6 = false; Vector<Object[]> tables = BasicSQLUtils.query(conn, "show tables"); for (Object[] tblRow : tables) { if (row[0].toString().equals("debugdb")) { System.err.println(tblRow[0].toString()); } if (tblRow[0].toString().equals("usysversion")) { isSp5 = true; break; } else if (tblRow[0].toString().equals("gift")) { isSp6 = true; break; } } if (isSp5 || isSp6) { String collName = null; Vector<Object[]> tableDesc = BasicSQLUtils.query(conn, "SELECT CollectionName FROM collection"); if (tableDesc.size() > 0) { collName = tableDesc.get(0)[0].toString(); } if (collName == null) { continue; } if (isSp5) { availOldPairs.add(new DBNamePair(collName, row[0].toString())); } else { availNewPairs.add(new DBNamePair(collName, row[0].toString())); } } System.err.println("isSp5 [" + isSp5 + "] isSp6 [" + isSp6 + "] "); } Comparator<Pair<String, String>> comparator = new Comparator<Pair<String, String>>() { @Override public int compare(Pair<String, String> o1, Pair<String, String> o2) { return o1.second.compareTo(o2.second); } }; Collections.sort(availOldPairs, comparator); Collections.sort(availNewPairs, comparator); mgr.close(); BasicSQLUtils.setSkipTrackExceptions(false); final JList oldlist = new JList(availOldPairs); final JList newList = new JList(availNewPairs); CellConstraints cc = new CellConstraints(); PanelBuilder pb = new PanelBuilder(new FormLayout("f:p:g,10px,f:p:g", "p,2px,f:p:g,4px,p")); pb.addSeparator("Specify 5 Databases", cc.xy(1, 1)); pb.add(UIHelper.createScrollPane(oldlist), cc.xy(1, 3)); pb.addSeparator("Specify 6 Databases", cc.xy(3, 1)); pb.add(UIHelper.createScrollPane(newList), cc.xy(3, 3)); ArrayList<String> list = new ArrayList<String>(labels.length); for (String s : labels) { list.add(s); } chkPanel = new ToggleButtonChooserPanel<String>(list, Type.Checkbox); chkPanel.setUseScrollPane(true); chkPanel.createUI(); //pb.add(chkPanel, cc.xyw(1, 5, 3)); /*ActionListener al = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { boolean isSelected = chkPanel.getButtons().get(0).isSelected(); int inx = chkPanel.getSelectedIndex(); if (inx == 0) { Vector<JToggleButton> btns = chkPanel.getButtons(); for (int i=1;i<btns.size();i++) { btns.get(i).setEnabled(!isSelected); } } } }; chkPanel.getButtons().get(0).addActionListener(al); chkPanel.getButtons().get(chkPanel.getButtons().size()-1).addActionListener(al);*/ ListSelectionListener oldDBListener = new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { if (!e.getValueIsAdjusting()) { DBNamePair pair = (DBNamePair) oldlist.getSelectedValue(); if (pair != null) { int index = 0; for (DBNamePair p : availNewPairs) { if (p.second.startsWith(pair.second)) { final int inx = index; SwingUtilities.invokeLater(new Runnable() { @Override public void run() { newList.setSelectedIndex(inx); newList.ensureIndexIsVisible(inx); } }); } index++; } } } } }; oldlist.getSelectionModel().addListSelectionListener(oldDBListener); MouseAdapter ma = new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { super.mouseClicked(e); Vector<JToggleButton> btns = chkPanel.getButtons(); if (e.getSource() == btns.get(0)) { boolean isSelected = btns.get(0).isSelected(); for (int i = 1; i < btns.size(); i++) { btns.get(i).setEnabled(!isSelected); } } else if (e.getSource() == btns.get(btns.size() - 1)) { boolean isSelected = btns.get(btns.size() - 1).isSelected(); for (int i = 0; i < btns.size() - 1; i++) { if (i > 0) btns.get(i).setSelected(!isSelected); btns.get(i).setEnabled(!isSelected); } } } }; chkPanel.getButtons().get(0).addMouseListener(ma); chkPanel.getButtons().get(chkPanel.getButtons().size() - 1).addMouseListener(ma); /*ChangeListener cl = new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { Vector<JToggleButton> btns = chkPanel.getButtons(); if (e.getSource() == btns.get(0)) { boolean isSelected = btns.get(0).isSelected(); System.out.println(isSelected); for (int i=1;i<btns.size();i++) { btns.get(i).setEnabled(!isSelected); } } else if (e.getSource() == btns.get(btns.size()-1)) { boolean isSelected = btns.get(0).isSelected(); System.out.println(isSelected); for (int i=0;i<btns.size()-1;i++) { btns.get(i).setEnabled(!isSelected); } } } }; chkPanel.getButtons().get(0).addChangeListener(cl); chkPanel.getButtons().get(chkPanel.getButtons().size()-1).addChangeListener(cl);*/ pb.setDefaultDialogBorder(); final CustomDialog dlg = new CustomDialog(null, "Select a DB to Verify", true, pb.getPanel()); ListSelectionListener lsl = new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { if (!e.getValueIsAdjusting()) { dlg.getOkBtn().setEnabled(oldlist.getSelectedIndex() > -1); } } }; oldlist.addListSelectionListener(lsl); newList.addListSelectionListener(lsl); oldlist.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); newList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); MouseAdapter listMA = new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) { dlg.getOkBtn() .setEnabled(oldlist.getSelectedIndex() > -1 && newList.getSelectedIndex() > -1); dlg.getOkBtn().doClick(); } } }; oldlist.addMouseListener(listMA); newList.addMouseListener(listMA); dlg.createUI(); dlg.pack(); //dlg.setSize(300, 800); dlg.pack(); dlg.setVisible(true); if (dlg.isCancelled()) { return null; } DBNamePair oldPair = (DBNamePair) oldlist.getSelectedValue(); namePairToConvert = (DBNamePair) newList.getSelectedValue(); namePairToConvert.first = oldPair.second; return namePairToConvert; } } catch (Exception ex) { } return null; }
From source file:edu.ku.brc.specify.tasks.subpane.qb.QueryBldrPane.java
/** * @param parentList/*from w ww . jav a 2s . c o m*/ */ protected void fillNextList(final JList parentList) { if (processingLists) { return; } processingLists = true; final int curInx = listBoxList.indexOf(parentList); if (curInx > -1) { int startSize = listBoxPanel.getComponentCount(); for (int i = curInx + 1; i < listBoxList.size(); i++) { listBoxPanel.remove(spList.get(i)); } int removed = startSize - listBoxPanel.getComponentCount(); for (int i = 0; i < removed; i++) { tableTreeList.remove(tableTreeList.size() - 1); } } else { listBoxPanel.removeAll(); tableTreeList.clear(); } QryListRendererIFace item = (QryListRendererIFace) parentList.getSelectedValue(); if (item instanceof ExpandableQRI) { JList newList; DefaultListModel model; JScrollPane sp; if (curInx == listBoxList.size() - 1) { newList = new JList(model = new DefaultListModel()); newList.addMouseListener(new MouseAdapter() { /* (non-Javadoc) * @see java.awt.event.MouseListener#mouseClicked(java.awt.event.MouseEvent) */ @Override public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) { if (currentInx != -1) { JList list = (JList) e.getSource(); QryListRendererIFace qriFace = (QryListRendererIFace) list.getSelectedValue(); if (BaseQRI.class.isAssignableFrom(qriFace.getClass())) { BaseQRI qri = (BaseQRI) qriFace; if (qri.isInUse()) { //remove the field for (QueryFieldPanel qfp : QueryBldrPane.this.queryFieldItems) { FieldQRI fqri = qfp.getFieldQRI(); if (fqri == qri || (fqri instanceof RelQRI && fqri.getTable() == qri)) { boolean clearIt = qfp.getSchemaItem() != null; QueryBldrPane.this.removeQueryFieldItem(qfp); if (clearIt) { qfp.setField(null, null); } break; } } } else { // add the field try { FieldQRI fieldQRI = buildFieldQRI(qri); if (fieldQRI == null) { throw new Exception("null FieldQRI"); } SpQueryField qf = new SpQueryField(); qf.initialize(); qf.setFieldName(fieldQRI.getFieldName()); qf.setStringId(fieldQRI.getStringId()); query.addReference(qf, "fields"); if (!isExportMapping) { addQueryFieldItem(fieldQRI, qf, false); } else { addNewMapping(fieldQRI, qf, null, false); } } catch (Exception ex) { log.error(ex); UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance() .capture(QueryBldrPane.class, ex); return; } } } } } } }); newList.setCellRenderer(qryRenderer); listBoxList.add(newList); sp = new JScrollPane(newList, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); JLabel colHeader = UIHelper.createLabel(item.getTitle()); colHeader.setHorizontalAlignment(SwingConstants.CENTER); colHeader.setBackground(listBoxPanel.getBackground()); colHeader.setOpaque(true); sp.setColumnHeaderView(colHeader); spList.add(sp); newList.getSelectionModel().addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { if (!e.getValueIsAdjusting()) { fillNextList(listBoxList.get(curInx + 1)); } } }); } else { newList = listBoxList.get(curInx + 1); model = (DefaultListModel) newList.getModel(); sp = spList.get(curInx + 1); JLabel colHeaderLbl = (JLabel) sp.getColumnHeader().getComponent(0); if (item instanceof TableQRI) { colHeaderLbl.setText(((TableQRI) item).getTitle()); } else { colHeaderLbl.setText(getResourceString("QueryBldrPane.QueryFields")); } } createNewList((TableQRI) item, model); listBoxPanel.remove(addBtn); listBoxPanel.add(sp); tableTreeList.add(((ExpandableQRI) item).getTableTree()); listBoxPanel.add(addBtn); currentInx = -1; } else { listBoxPanel.add(addBtn); } SwingUtilities.invokeLater(new Runnable() { public void run() { updateAddBtnState(); // Is all this really necessary listBoxPanel.validate(); listBoxPanel.repaint(); scrollPane.validate(); scrollPane.invalidate(); scrollPane.doLayout(); scrollPane.repaint(); validate(); invalidate(); doLayout(); repaint(); UIRegistry.forceTopFrameRepaint(); } }); processingLists = false; currentInx = curInx; }