Java Code Examples for javax.swing.JList#getSelectedIndex()

The following examples show how to use javax.swing.JList#getSelectedIndex() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ScrTypes.java    From PolyGlot with MIT License 6 votes vote down vote up
private void lstTypesValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_lstTypesValueChanged
    if (evt.getValueIsAdjusting()
            || updatingName
            || ignoreUpdate) {
        return;
    }

    if (evt.getFirstIndex() != evt.getLastIndex()) {
        JList list = (JList) evt.getSource();
        int selected = list.getSelectedIndex();
        int index = selected == evt.getFirstIndex()
                ? evt.getLastIndex() : evt.getFirstIndex();

        if (index != -1) {
            TypeNode curNode = lstTypes.getModel().getElementAt(index);

            if (curNode != null) {
                savePropertiesTo(curNode);
            }
        }
    }

    populateProperties();
}
 
Example 2
Source File: AbstractPageListPopupListener.java    From wpcleaner with Apache License 2.0 6 votes vote down vote up
/**
 * Show popup menu in response to a key event.
 * 
 * @param e Event.
 */
@Override
protected void showPopup(KeyEvent e) {

  // Retrieve information
  if (!(e.getComponent() instanceof JList)) {
    return;
  }
  JList tmpList = (JList) e.getComponent();
  int position = tmpList.getSelectedIndex();
  if (position < 0) {
    return;
  }
  Object object = tmpList.getModel().getElementAt(position);
  if (!(object instanceof Page)) {
    return;
  }
  Page link = (Page) object;
  Rectangle rect = tmpList.getCellBounds(position, position);
  showPopup(tmpList, link, (int) rect.getMinX(), (int) rect.getMaxY());
}
 
Example 3
Source File: ComboboxRenderer.java    From WorldGrower with GNU General Public License v3.0 6 votes vote down vote up
@Override
public Component getListCellRendererComponent(JList list, Object value,
                    int index, boolean isSelected, boolean cellHasFocus) {

    JComponent comp = (JComponent) super.getListCellRendererComponent(list,
            value, index, isSelected, cellHasFocus);

    if (index == -1) {
    	index = list.getSelectedIndex();
    }
    
    if (index != -1) {
    	if (tooltips != null) {
    		list.setToolTipText(tooltips[index]);
    	}
    	if (images != null) {
    		setIcon(new ImageIcon(images[index]));
    	}
    }
    return comp;
}
 
Example 4
Source File: ComponentController.java    From swingsane with Apache License 2.0 6 votes vote down vote up
private void scannerListSelectionChanged(ListSelectionEvent e) {
  if (!(e.getValueIsAdjusting())) {
    return;
  }
  @SuppressWarnings("unchecked")
  JList<ScannerListItem> scannerList = (JList<ScannerListItem>) e.getSource();
  if (scannerList.getSelectedIndex() < 0) {
    disableSettingsComponents();
    disableScanButtons();
    return;
  }
  disableSettingsComponents();
  ScannerListItem scannerListItem = scannerList.getSelectedValue();
  Scanner scanner = scannerListItem.getScanner();
  adjustSettingsComponents(scanner);
  enableScanButtons();
  updateComponents(scannerListItem);
}
 
Example 5
Source File: Utility.java    From iBioSim with Apache License 2.0 6 votes vote down vote up
/**
 * Adds a new item to a JList
 */
public static void add(JList currentList, Object newItem) {
	Object[] list = new Object[currentList.getModel().getSize() + 1];
	int addAfter = currentList.getSelectedIndex();
	for (int i = 0; i <= currentList.getModel().getSize(); i++) {
		if (i <= addAfter) {
			list[i] = currentList.getModel().getElementAt(i);
		}
		else if (i == (addAfter + 1)) {
			list[i] = newItem;
		}
		else {
			list[i] = currentList.getModel().getElementAt(i - 1);
		}
	}
	currentList.setListData(list);
}
 
Example 6
Source File: Events.java    From iBioSim with Apache License 2.0 6 votes vote down vote up
/**
 * Remove an event from a list and SBML gcm.getSBMLDocument()
 * 
 * @param events
 *            a list of events
 * @param gcm.getSBMLDocument()
 *            an SBML gcm.getSBMLDocument() from which to remove the event
 * @param usedIDs
 *            a list of all IDs current in use
 * @param ev
 *            an array of all events
 */
private void removeEvent(JList events, BioModel gcm) {
	int index = events.getSelectedIndex();
	if (index != -1) {
		String selected = ((String) events.getSelectedValue()).split("\\[")[0];
		removeTheEvent(gcm, selected);
		events.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
		Utility.remove(events);
		events.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		if (index < events.getModel().getSize()) {
			events.setSelectedIndex(index);
		}
		else {
			events.setSelectedIndex(index - 1);
		}
		modelEditor.setDirty(true);
		modelEditor.makeUndoPoint();
	}
}
 
Example 7
Source File: CheckList.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void actionPerformed(ActionEvent e) {
JList list = (JList) e.getSource();
       int index = list.getSelectedIndex();
       if (index < 0)
           return;
       CheckListModel model = (CheckListModel) list.getModel();
       model.setChecked(index, !model.isChecked(index));
   }
 
Example 8
Source File: ScrLexicon.java    From PolyGlot with MIT License 5 votes vote down vote up
private void lstLexiconValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_lstLexiconValueChanged
    if (evt.getValueIsAdjusting()
            || namePopulating
            || forceUpdate) {
        return;
    }

    if (!curPopulating
            && evt.getFirstIndex() != evt.getLastIndex()) {
        JList list = (JList) evt.getSource();
        int selected = list.getSelectedIndex();
        int index = selected == evt.getFirstIndex()
                ? evt.getLastIndex() : evt.getFirstIndex();

        if (index != -1
                && index < lstLexicon.getModel().getSize()) {
            ConWord saveWord = lstLexicon.getModel().getElementAt(index).getConWord();
            saveValuesTo(saveWord);
        }
        
        txtErrorBox.setText("");
    }

    populateProperties();

    // if looking for illegals, always check legality value of word, otherwise let it slide for user convenience
    if (chkFindBad.isSelected()) {
        setWordLegality();
    }
}
 
Example 9
Source File: PackagePanel.java    From constellation with Apache License 2.0 5 votes vote down vote up
/**
 * Updates label and enables/disables ok button.
 */
private static void updateLabelEtcFromList(final JTextField field, final JList<String> list, final List<File> dirs, final JButton okButton) {
    int idx = list.getSelectedIndex();
    if (idx == -1) {
        field.setText(" "); // NOI18N
        field.getAccessibleContext().setAccessibleName(" ");
        okButton.setEnabled(false);
    } else {
        final File dir = dirs.get(idx);
        field.setText(NbBundle.getMessage(PackagePanel.class, "LBL_dirWillBe", dir.getAbsolutePath()));
        field.getAccessibleContext().setAccessibleName(NbBundle.getMessage(PackagePanel.class, "LBL_dirWillBe", dir.getAbsolutePath()));
        okButton.setEnabled(true);
    }
}
 
Example 10
Source File: GitUtils.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public QuickSearchCallback (List<T> items, JList component, DefaultListModel model, SearchCallback<T> callback) {
    this.items = new ArrayList<T>(items);
    results = new ArrayList<T>(items);
    this.component = component;
    this.model = model;
    this.callback = callback;
    this.currentPosition = component.getSelectedIndex();
    component.addListSelectionListener(this);
}
 
Example 11
Source File: Events.java    From iBioSim with Apache License 2.0 5 votes vote down vote up
/**
 * Remove an event assignment
 * 
 * @param eventAssign
 *            Jlist of event assignments for selected event
 * @param assign
 *            String array of event assignments for selected event
 */
private static void removeAssignment(JList eventAssign) {
	int index = eventAssign.getSelectedIndex();
	if (index != -1) {
		eventAssign.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
		Utility.remove(eventAssign);
		eventAssign.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		if (index < eventAssign.getModel().getSize()) {
			eventAssign.setSelectedIndex(index);
		}
		else {
			eventAssign.setSelectedIndex(index - 1);
		}
	}
}
 
Example 12
Source File: CheckList.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void actionPerformed(ActionEvent e) {
JList list = (JList) e.getSource();
       int index = list.getSelectedIndex();
       if (index < 0)
           return;
       CheckListModel model = (CheckListModel) list.getModel();
       model.setChecked(index, !model.isChecked(index));
   }
 
Example 13
Source File: CodeCompletionPanel.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void javaCompletionExcluderEditButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_javaCompletionExcluderEditButtonActionPerformed
    JList list = getSelectedExcluderList();
    int index = list.getSelectedIndex();
    if (index == -1)
    return;
    DefaultListModel model = (DefaultListModel) list.getModel();
    javaExcluderEditing = (String) model.getElementAt(index);
    openExcluderEditor();
}
 
Example 14
Source File: DownloadMapsWindow.java    From triplea with GNU General Public License v3.0 5 votes vote down vote up
private static ListSelectionListener newDescriptionPanelUpdatingSelectionListener(
    final JEditorPane descriptionPanel,
    final JList<String> gamesList,
    final List<DownloadFileDescription> maps,
    final MapAction action,
    final JLabel mapSizeLabelToUpdate) {
  return e -> {
    if (!e.getValueIsAdjusting()) {
      final int index = gamesList.getSelectedIndex();

      final boolean somethingIsSelected = index >= 0;
      if (somethingIsSelected) {
        final String mapName = gamesList.getModel().getElementAt(index);

        // find the map description by map name and update the map download detail panel
        final Optional<DownloadFileDescription> map =
            maps.stream()
                .filter(mapDescription -> mapDescription.getMapName().equals(mapName))
                .findFirst();
        if (map.isPresent()) {
          final String text = map.get().toHtmlString();
          descriptionPanel.setText(text);
          descriptionPanel.scrollRectToVisible(new Rectangle(0, 0, 0, 0));
          updateMapUrlAndSizeLabel(map.get(), action, mapSizeLabelToUpdate);
        }
      }
    }
  };
}
 
Example 15
Source File: CommonSettingsDialog.java    From megamek with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void mouseDragged(MouseEvent e) {
    Object src = e.getSource();
    if (mouseDragging && (src instanceof JList)) {
        JList<?> srcList = (JList<?>) src;
        DefaultListModel<?> srcModel = (DefaultListModel<?>) srcList.getModel();
        int currentIndex = srcList.locationToIndex(e.getPoint());
        if (currentIndex != dragSourceIndex) {
            int dragTargetIndex = srcList.getSelectedIndex();
            moveElement(srcModel, dragSourceIndex, dragTargetIndex);
            dragSourceIndex = currentIndex;
        }
    }
}
 
Example 16
Source File: WeaponPanel.java    From megamek with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void mouseDragged(MouseEvent e) {
    removeListeners();
    
    Object src = e.getSource();
    // Check to see if we are in a state we care about
    if (!mouseDragging || !(src instanceof JList)) {
        return;
    }
    JList<?> srcList = (JList<?>) src;
    WeaponListModel srcModel = (WeaponListModel) srcList.getModel();
    int currentIndex = srcList.locationToIndex(e.getPoint());
    if (currentIndex != dragSourceIndex) {
        int dragTargetIndex = srcList.getSelectedIndex();
        Mounted weap1 = srcModel.getWeaponAt(dragSourceIndex);
        srcModel.swapIdx(dragSourceIndex, dragTargetIndex);
        dragSourceIndex = currentIndex;
        Entity ent = weap1.getEntity();
        // Is the sort order custom?
        int customId = Entity.WeaponSortOrder.CUSTOM.ordinal();
        // Update weap sort order drop down
        if (weapSortOrder.getSelectedIndex() != customId) {
            // Set the order to custom
            ent.setWeaponSortOrder(Entity.WeaponSortOrder.CUSTOM);
            weapSortOrder.setSelectedIndex(customId);
        }
        // Update custom order
        for (int i = 0; i < srcModel.getSize(); i++) {
            Mounted m = srcModel.getWeaponAt(i);
            ent.setCustomWeaponOrder(m, i);
        }
        if (unitDisplay.getClientGUI() != null) {
            unitDisplay.getClientGUI().getMenuBar()
                    .updateSaveWeaponOrderMenuItem();
        }
    }
    addListeners();
}
 
Example 17
Source File: ListTransferHandler.java    From marathonv5 with Apache License 2.0 5 votes vote down vote up
protected void importString(JComponent c, String str) {
    JList target = (JList) c;
    DefaultListModel listModel = (DefaultListModel) target.getModel();
    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.
    // So this is not allowed.
    if (indices != null && index >= indices[0] - 1 && index <= indices[indices.length - 1]) {
        indices = null;
        return;
    }

    int max = listModel.getSize();
    if (index < 0) {
        index = max;
    } else {
        index++;
        if (index > max) {
            index = max;
        }
    }
    addIndex = index;
    String[] values = str.split("\n");
    addCount = values.length;
    for (String value : values) {
        listModel.add(index++, value);
    }
}
 
Example 18
Source File: EditIDSControlPanel.java    From VanetSim with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void valueChanged(ListSelectionEvent arg0) {
	@SuppressWarnings("unchecked")
	JList<Object> list = (JList<Object>) arg0.getSource();
	
	if(!list.getValueIsAdjusting() && list.getSelectedIndex() != -1){

		if(list.getModel().equals(availableRulesModel)){
			updateList("available", availableRulesModel.get(list.getSelectedIndex()).toString());
		}
		else if (list.getModel().equals(selectedRulesModel)){
			updateList("selected", selectedRulesModel.get(list.getSelectedIndex()).toString());
		}
	}
}
 
Example 19
Source File: DifferencesManagementPanel.java    From swift-explorer with Apache License 2.0 4 votes vote down vote up
private boolean isItemSelected(JList<ComparisonItem> list)
{
	return list.getSelectedIndex() >= 0;
}
 
Example 20
Source File: NullpoMinoSwing.java    From nullpomino with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * Init top screen
 */
protected void initTopScreenUI(JComponent p) {
	p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));

	// Label
	lModeSelect = new JLabel(getUIText("Top_ModeSelect"));
	lModeSelect.setAlignmentX(0f);
	p.add(lModeSelect);

	// Mode & rule select panel
	JPanel subpanelModeSelect = new JPanel(new BorderLayout());
	subpanelModeSelect.setBorder(new EtchedBorder());
	subpanelModeSelect.setAlignmentX(0f);
	p.add(subpanelModeSelect);

	// * Mode select listbox
	listboxMode = new JList(modeList);
	listboxMode.addMouseListener(new ListboxModeMouseAdapter());
	listboxMode.addListSelectionListener(new ListSelectionListener() {
		public void valueChanged(ListSelectionEvent e) {
			String strMode = (String)listboxMode.getSelectedValue();
			lModeSelect.setText(getModeDesc(strMode));
			prepareRuleList(strMode);
		}
	});
	JScrollPane scpaneListboxMode = new JScrollPane(listboxMode);
	scpaneListboxMode.setPreferredSize(new Dimension(280, 375));
	subpanelModeSelect.add(scpaneListboxMode, BorderLayout.WEST);

	// * Rule select listbox
	listmodelRule = new DefaultListModel();
	listboxRule = new JList(listmodelRule);
	listboxRule.addMouseListener(new ListboxModeMouseAdapter());
	JScrollPane scpaneListBoxRule = new JScrollPane(listboxRule);
	scpaneListBoxRule.setPreferredSize(new Dimension(150, 375));
	subpanelModeSelect.add(scpaneListBoxRule, BorderLayout.CENTER);

	// * Set default selected index
	listboxMode.setSelectedValue(propGlobal.getProperty("name.mode", ""), true);
	if(listboxMode.getSelectedIndex() == -1) listboxMode.setSelectedIndex(0);
	prepareRuleList((String)listboxMode.getSelectedValue());

	// Start button
	JButton buttonStartOffline = new JButton(getUIText("Top_StartOffline"));
	buttonStartOffline.setMnemonic('S');
	buttonStartOffline.addActionListener(this);
	buttonStartOffline.setActionCommand("Top_StartOffline");
	buttonStartOffline.setAlignmentX(0f);
	buttonStartOffline.setMaximumSize(new Dimension(Short.MAX_VALUE, buttonStartOffline.getMaximumSize().height));
	p.add(buttonStartOffline);
	this.getRootPane().setDefaultButton(buttonStartOffline);

	// Menu
	initMenu();
}