Java Code Examples for javax.swing.ListModel

The following examples show how to use javax.swing.ListModel. These examples are extracted from open source projects. 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 Project: ghidra   Source File: DisassembledViewPluginTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Tests the plugins response to {@link ProgramSelectionPluginEvent}s.
 * 
 * @throws Exception If there is a problem opening the program.
 */
@Test
public void testProcessingOnSelectionChanged() throws Exception {
	openProgram("notepad");

	tool.showComponentProvider(componentProvider, true);
	waitForPostedSwingRunnables();

	// the Java component that is our display for the plugin
	JList list = (JList) getInstanceField("contentList", componentProvider);
	ListModel listContents = list.getModel();

	// make sure that nothing happens on a single-selection     
	plugin.processEvent(createProgramSelectionEvent(false));

	assertTrue("The list is not the same after processing a " + "single-selection event.",
		compareListData(listContents, list.getModel()));

	// make sure that the component display is cleared when there is a 
	// multiple-selection
	plugin.processEvent(createProgramSelectionEvent(true));

	assertTrue(
		"The list content did not change after processing a " + "multiple-selection event.",
		!compareListData(listContents, list.getModel()));
}
 
Example 2
protected void setScriptingLanguage( final String lang, final JComboBox languageField ) {
  if ( lang == null ) {
    languageField.setSelectedItem( null );
    return;
  }

  final ListModel model = languageField.getModel();
  for ( int i = 0; i < model.getSize(); i++ ) {
    final ScriptEngineFactory elementAt = (ScriptEngineFactory) model.getElementAt( i );
    if ( elementAt == null ) {
      continue;
    }
    if ( elementAt.getNames().contains( lang ) ) {
      languageField.setSelectedItem( elementAt );
      return;
    }
  }
}
 
Example 3
Source Project: netbeans   Source File: CategoryPanelFormatters.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean isChanged() {
    ListModel formattersModel = formattersList.getModel();
    VariablesFormatter[] formatters = new VariablesFormatter[formattersModel.getSize()];
    for (int i = 0; i < formatters.length; i++) {
        formatters[i] = (VariablesFormatter) formattersModel.getElementAt(i);
    }
    VariablesFormatter[] saved = VariablesFormatter.loadFormatters();
    if(saved == null) {
        return false;
    }
    if(saved.length != formatters.length) {
        return true;
    }
    for (int i = 0; i < saved.length; i++) {
        VariablesFormatter savedFormatter = saved[i];
        VariablesFormatter currentFormatter = (VariablesFormatter) formattersModel.getElementAt(i);
        if(!areVariablesFormattersEqual(savedFormatter, currentFormatter)) {
            return true;
        }
    }
    return false;
}
 
Example 4
Source Project: ramus   Source File: TableRowHeader.java    License: GNU General Public License v3.0 6 votes vote down vote up
private void updatePrefferedWidth(int firstRow, int lastRow) {
    final ListModel model = getModel();
    final int l = model.getSize() - 1;
    if (lastRow > l)
        lastRow = l;
    if (firstRow < 0)
        firstRow = 0;
    int m = this.m;
    for (int i = firstRow; i <= lastRow; i++) {
        final Object obj = model.getElementAt(i);
        if (obj == null)
            continue;
        final Component c = renderer.getListCellRendererComponent(this,
                obj, i, true, true);
        final int t = c.getPreferredSize().width + 2;
        if (t > m)
            m = t;
    }
    if (m != getFixedCellWidth()) {
        setFixedCellWidth(m);
        revalidate();
    }
}
 
Example 5
Source Project: pdfxtk   Source File: MultiColumnListUI.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Paint one List cell: compute the relevant state, get the "rubber stamp"
 * cell renderer component, and then use the CellRendererPane to paint it.
 * Subclasses may want to override this method rather than paint().
 *
 * @see #paint
 */
protected void paintCell(
	   Graphics g,
	   int row,
	   Rectangle rowBounds,
	   ListCellRenderer cellRenderer,
	   ListModel dataModel,
	   ListSelectionModel selModel,
	   int leadIndex)
{
  Object value = dataModel.getElementAt(row);
  boolean cellHasFocus = list.hasFocus() && (row == leadIndex);
  boolean isSelected = selModel.isSelectedIndex(row);

  Component rendererComponent =
    cellRenderer.getListCellRendererComponent(list, value, row, isSelected, cellHasFocus);

  int cx = rowBounds.x;
  int cy = rowBounds.y;
  int cw = rowBounds.width;
  int ch = rowBounds.height;
  rendererPane.paintComponent(g, rendererComponent, list, cx, cy, cw, ch, true);
}
 
Example 6
Source Project: freecol   Source File: UnitType.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public int getMaximumIndex(Colony colony, JList<BuildableType> buildQueueList, int UNABLE_TO_BUILD) {
    ListModel<BuildableType> buildQueue = buildQueueList.getModel();
    final int buildQueueLastPos = buildQueue.getSize();

    boolean canBuild = false;
    if (colony.canBuild(this)) {
        canBuild = true;
    }

    // does not depend on anything, nothing depends on it
    // can be built at any time
    if (canBuild) return buildQueueLastPos;
    // check for building in queue that allows builting this unit
    for (int index = 0; index < buildQueue.getSize(); index++) {
        BuildableType toBuild = buildQueue.getElementAt(index);
        if (toBuild == this) continue;
        if (toBuild.hasAbility(Ability.BUILD, this)) {
            return buildQueueLastPos;
        }
    }
    return UNABLE_TO_BUILD;
}
 
Example 7
protected void setScriptingLanguage( final String lang, final JComboBox languageField ) {
  if ( lang == null ) {
    languageField.setSelectedItem( null );
    return;
  }

  final ListModel model = languageField.getModel();
  for ( int i = 0; i < model.getSize(); i++ ) {
    final ScriptEngineFactory elementAt = (ScriptEngineFactory) model.getElementAt( i );
    if ( elementAt == null ) {
      continue;
    }
    if ( elementAt.getNames().contains( lang ) ) {
      languageField.setSelectedItem( elementAt );
      return;
    }
  }
}
 
Example 8
Source Project: wandora   Source File: QueryLibraryPanel.java    License: GNU General Public License v3.0 6 votes vote down vote up
public void saveClicked(){
    String name=nameField.getText().trim();
    if(name.length()==0){
        WandoraOptionPane.showMessageDialog(Wandora.getWandora(), "Name is empty.");
        return;
    }
    else {
        ListModel listModel=queryList.getModel();
        for(int i=0;i<listModel.getSize();i++){
            Object o=listModel.getElementAt(i);
            if(name.equals(o)){
                if(openedName==null || !openedName.equals(name)){
                    // TODO: confirm overwrite
                }
                break;
            }
        }
    }
    
    openedName=name;
    
    save(name);
}
 
Example 9
Source Project: netbeans   Source File: TaskPanel.java    License: Apache License 2.0 6 votes vote down vote up
private void reloadField (JComponent component, IssueField field) {
    String newValue;
    newValue = task.getFieldValue(field);
    boolean fieldDirty = unsavedFields.contains(field.getKey());
    if (!fieldDirty) {
        if (component instanceof JComboBox) {
            throw new UnsupportedOperationException();
        } else if (component instanceof JTextComponent) {
            ((JTextComponent) component).setText(newValue);
        } else if (component instanceof JList) {
            JList list = (JList) component;
            list.clearSelection();
            ListModel model = list.getModel();
            for (String value : task.getFieldValues(field)) {
                for (int i = 0; i < model.getSize(); i++) {
                    if (value.equals(model.getElementAt(i))) {
                        list.addSelectionInterval(i, i);
                    }
                }
            }
        } else if (component instanceof JCheckBox) {
            ((JCheckBox) component).setSelected("1".equals(newValue));
        }
    }
}
 
Example 10
Source Project: iBioSim   Source File: AnalysisView.java    License: Apache License 2.0 6 votes vote down vote up
public boolean reb2sacAbstraction()
{
  ListModel<String> preAbsList = preAbs.getModel();
  for (int i = 0; i < preAbsList.getSize(); i++)
  {
    String abstractionOption = (String) preAbsList.getElementAt(i);
    if (!abstractionOption.equals("complex-formation-and-sequestering-abstraction") && !abstractionOption.equals("operator-site-reduction-abstraction"))
    {
      return true;
    }
  }
  ListModel<String> loopAbsList = loopAbs.getModel();
  if (loopAbsList.getSize() > 0)
  {
    return true;
  }
  ListModel<String> postAbsList = postAbs.getModel();
  if (postAbsList.getSize() > 0)
  {
    return true;
  }
  return false;
}
 
Example 11
Source Project: netbeans   Source File: GoToPanelImpl.java    License: Apache License 2.0 6 votes vote down vote up
/** Sets the model.
 * Threading: Requires EDT.
 * @param the model to set
 * @param finished true for final update
 * @return true if model has changed
 */
@Override
public boolean setModel(
        @NonNull final ListModel model,
        final boolean finished) {
    assert SwingUtilities.isEventDispatchThread();
    matchesList.setModel(model);
    if (model.getSize() > 0 || getText() == null || getText().trim().length() == 0 ) {
        matchesList.setSelectedIndex(0);
        setListPanelContent(null,false);
        if ( time != -1 ) {
            GoToSymbolAction.LOGGER.log(
                    Level.FINE,
                    "Real search time {0} ms.",    //NOI18N
                    (System.currentTimeMillis() - time));
            time = -1;
        }
        return true;
    } else if (finished) {
        setListPanelContent(NbBundle.getMessage(GoToPanelImpl.class, "TXT_NoSymbolsFound") ,false );
        return false;
    } else {
        return false;
    }
}
 
Example 12
Source Project: zap-extensions   Source File: WebSocketUiHelper.java    License: Apache License 2.0 6 votes vote down vote up
public void setSelectedChannelIds(List<Integer> channelIds) {
    JList<WebSocketChannelDTO> channelsList = getChannelsList();
    if (channelIds == null || channelIds.contains(-1)) {
        channelsList.setSelectedIndex(0);
    } else {
        int[] selectedIndices = new int[channelIds.size()];
        ListModel<WebSocketChannelDTO> model = channelsList.getModel();
        for (int i = 0, j = 0; i < model.getSize(); i++) {
            WebSocketChannelDTO channel = model.getElementAt(i);
            if (channelIds.contains(channel.id)) {
                selectedIndices[j++] = i;
            }
        }
        channelsList.setSelectedIndices(selectedIndices);
    }
}
 
Example 13
Source Project: binnavi   Source File: CProjectNodeComponent.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Because the checked list box can not yet deal with growing or shrinking models, the checked
 * list box is recreated by this function if necessary.
 */
private void updateCheckedListPanel() {
  m_checkedList.removeListSelectionListener(m_updateListener);
  m_checkedListPanel.removeAll();
  m_checkedList = new JCheckedListbox<>(getDebuggerVector(), false);
  m_checkedList.addListSelectionListener(m_updateListener);
  final JScrollPane debuggerScrollPane = new JScrollPane(m_checkedList);
  m_checkedListPanel.add(debuggerScrollPane);
  final Collection<DebuggerTemplate> debuggers = m_project.getConfiguration().getDebuggers();
  final ListModel<DebuggerTemplate> model = m_checkedList.getModel();
  for (int i = 0; i < model.getSize(); ++i) {
    final DebuggerTemplate debuggerId = model.getElementAt(i);
    m_checkedList.setChecked(i, debuggers.contains(debuggerId));
  }
  m_checkedList.updateUI();
  updateUI();
}
 
Example 14
Source Project: pdfxtk   Source File: MultiColumnListUI.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Create and install the listeners for the JList, its model, and its
 * selectionModel.  This method is called at installUI() time.
 *
 * @see #installUI
 * @see #uninstallListeners
 */
protected void installListeners()
{
  focusListener = createFocusListener();
  mouseInputListener = createMouseInputListener();
  propertyChangeListener = createPropertyChangeListener();
  listSelectionListener = createListSelectionListener();
  listDataListener = createListDataListener();

  list.addFocusListener(focusListener);
  list.addMouseListener(mouseInputListener);
  list.addMouseMotionListener(mouseInputListener);
  list.addPropertyChangeListener(propertyChangeListener);

  ListModel model = list.getModel();
  if (model != null) {
    model.addListDataListener(listDataListener);
  }

  ListSelectionModel selectionModel = list.getSelectionModel();
  if (selectionModel != null) {
    selectionModel.addListSelectionListener(listSelectionListener);
  }
}
 
Example 15
@Override
public void restoreModels(ModelMap models)
{
	pageList.setModel(models.get(ListModel.class));
	pageList.setSelectionModel(models.get(ListSelectionModel.class));
	models.get(NoteListHandler.class).install();
	models.get(PageHandler.class).install();
	addButton.setAction(models.get(AddAction.class));
}
 
Example 16
Source Project: astor   Source File: FontChooserPanel.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Initializes the contents of the dialog from the given font
 * object.
 *
 * @param font the font from which to read the properties.
 */
public void setSelectedFont( Font font) {
    if (font == null) {
        throw new NullPointerException();
    }
    this.bold.setSelected(font.isBold());
    this.italic.setSelected(font.isItalic());

    String fontName = font.getName();
    ListModel model = this.fontlist.getModel();
    this.fontlist.clearSelection();
    for (int i = 0; i < model.getSize(); i++) {
        if (fontName.equals(model.getElementAt(i))) {
            this.fontlist.setSelectedIndex(i);
            break;
        }
    }

    String fontSize = String.valueOf(font.getSize());
    model = this.sizelist.getModel();
    this.sizelist.clearSelection();
    for (int i = 0; i < model.getSize(); i++) {
        if (fontSize.equals(model.getElementAt(i))) {
            this.sizelist.setSelectedIndex(i);
            break;
        }
    }
}
 
Example 17
Source Project: jdal   Source File: ListAccessor.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Collection<?> getControlValue() {
	List <Object> l = new ArrayList<Object>();
	ListModel lm = getControl().getModel();

	for (int i = 0; i < lm.getSize(); i++)
		l.add(lm.getElementAt(i));
	
	return l;
}
 
Example 18
Source Project: netbeans   Source File: CategoryPanelFormatters.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void store() {
    /*if (selectedVariablesFormatter != null) {
        storeSelectedFormatter(selectedVariablesFormatter);
    }*/
    Properties p = Properties.getDefault().getProperties("debugger.options.JPDA");
    ListModel formattersModel = formattersList.getModel();
    VariablesFormatter[] formatters = new VariablesFormatter[formattersModel.getSize()];
    for (int i = 0; i < formatters.length; i++) {
        VariablesFormatter vf = (VariablesFormatter) formattersModel.getElementAt(i);
        formatters[i] = vf;
    }
    p.setArray("VariableFormatters", formatters);
}
 
Example 19
Source Project: pumpernickel   Source File: ListKeyListener.java    License: MIT License 5 votes vote down vote up
@Override
protected boolean changeSelectionUsingText(KeyEvent e, String inputStr) {
	inputStr = inputStr.toUpperCase();
	ListCellRenderer renderer = getCellRenderer();

	List<Integer> itemsStartingWithText = new ArrayList<Integer>();

	ListModel model = getListModel();
	for (int a = 0; a < model.getSize(); a++) {
		Object element = model.getElementAt(a);
		Component rendered = renderer.getListCellRendererComponent(list,
				element, a, false, false);
		String text = getText(rendered);
		if (text == null)
			continue;
		text = text.toUpperCase();

		if (text.startsWith(inputStr)) {
			itemsStartingWithText.add(a);
		}
	}

	int selIndex = getSelectedIndex();

	int indexOf = itemsStartingWithText.indexOf(selIndex);
	int newSelIndex = selIndex;
	if (indexOf == -1) {
		if (itemsStartingWithText.size() > 0) {
			newSelIndex = itemsStartingWithText.get(0);
		}
	} else {
		int newIndex = (indexOf + 1) % itemsStartingWithText.size();
		newSelIndex = itemsStartingWithText.get(newIndex);
	}
	if (newSelIndex != selIndex) {
		setSelectedIndex(newSelIndex);
	}
	return newSelIndex != selIndex;
}
 
Example 20
Source Project: Zettelkasten   Source File: ListUtil.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * This method selects the first entry in the JList {@code list} that start with the
 * text that is entered in the filter-textfield {@code textfield}.
 *
 * @param list the JList where the item should be selected
 * @param textfield the related filtertextfield that contains the user-input
 */
public static void selectByTyping(javax.swing.JList list, javax.swing.JTextField textfield) {
    String text = textfield.getText().toLowerCase();
    ListModel lm = list.getModel();
    for (int cnt = 0; cnt < lm.getSize(); cnt++) {
        String val = lm.getElementAt(cnt).toString();
        if (val.toLowerCase().startsWith(text)) {
            list.setSelectedIndex(cnt);
            list.ensureIndexIsVisible(cnt);
            // and leave method
            return;
        }
    }
}
 
Example 21
Source Project: bigtable-sql   Source File: EditWhereColsPanel.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Move selected fields from "used" to "not used"
 */
private void moveToNotUsed() {
	
	// get the values from the "not use" list and convert to sorted set
	ListModel notUseColsModel = notUseColsList.getModel();
	SortedSet<String> notUseColsSet = new TreeSet<String>();
	for (int i=0; i<notUseColsModel.getSize(); i++)
		notUseColsSet.add((String)notUseColsModel.getElementAt(i));
	
	// get the values from the "use" list
	ListModel useColsModel = useColsList.getModel();
	
	// create an empty set for the "use" list
	SortedSet<Object> useColsSet = new TreeSet<Object>();

	// for each element in the "use" set, if selected then add to "not use",
	// otherwise add to new "use" set
	for (int i=0; i<useColsModel.getSize(); i++) {
		String colName = (String)useColsModel.getElementAt(i);
		if (useColsList.isSelectedIndex(i))
			notUseColsSet.add(colName);
		else useColsSet.add(colName);
	}
	
	useColsList.setListData(useColsSet.toArray());
	notUseColsList.setListData(notUseColsSet.toArray());
}
 
Example 22
Source Project: netbeans   Source File: FileListPanel.java    License: Apache License 2.0 5 votes vote down vote up
public List<String> getFiles(){
    Vector<String> files = new Vector<String>();
    ListModel lm = this.listFiles.getModel();
    int numFiles = lm.getSize();
    if (numFiles > 0){
        for (int i=0; i < numFiles; i++){
            files.add((String) lm.getElementAt(i));
        }
    }
    return files;
}
 
Example 23
Source Project: pumpernickel   Source File: ListLocationBrowserUI.java    License: MIT License 5 votes vote down vote up
public void run() {
	synchronizeDirectoryContents();
	if (adjustingModels > 0)
		return;
	adjustingModels++;
	try {
		IOLocation[] obj = browser.getSelectionModel().getSelection();
		List<Integer> ints = new ArrayList<Integer>();
		ListModel listModel = browser.getListModel();
		synchronized (listModel) {
			for (int a = 0; a < obj.length; a++) {
				int k = getIndexOf(listModel, obj[a]);
				if (k != -1) {
					ints.add(new Integer(k));
				}
			}
			int[] indices = new int[ints.size()];
			for (int a = 0; a < ints.size(); a++) {
				indices[a] = (ints.get(a)).intValue();
			}
			// seriously? there isn't a way to set the selection all at
			// once?
			table.getSelectionModel().clearSelection();
			for (int a = 0; a < indices.length; a++) {
				table.getSelectionModel().addSelectionInterval(
						indices[a], indices[a]);
			}

			if (indices.length > 0) {
				Rectangle r = table.getCellRect(indices[0], 0, false);
				table.scrollRectToVisible(r);
			}
		}
	} finally {
		adjustingModels--;
	}
}
 
Example 24
Source Project: Course_Generator   Source File: FontChooser.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Select the font name in the font name component
 * 
 * @param font Font where to get the font name to search to search
 */
private void SelectInFontList(Font font) {
	String str;
	ListModel<String> lm = jFontList.getModel();
	for (int i = 0; i < lm.getSize(); i++) {
		str = (String) lm.getElementAt(i);
		if (str.equalsIgnoreCase(font.getFamily())) {
			jFontList.setSelectedIndex(i);
			jFontList.ensureIndexIsVisible(i);
			return;
		}
	}
}
 
Example 25
Source Project: netbeans   Source File: MethodCandidateChooser.java    License: Apache License 2.0 5 votes vote down vote up
private ListModel createListModel() {
    DefaultListModel dlm = new DefaultListModel();
    
    for (Candidate cand: toShow) {
        dlm.addElement(cand);
    }
    
    return dlm;
}
 
Example 26
Source Project: netbeans   Source File: IsOverriddenPopup.java    License: Apache License 2.0 5 votes vote down vote up
private ListModel createListModel() {
    DefaultListModel dlm = new DefaultListModel();
    
    for (ElementDescription el: declarations) {
        dlm.addElement(el);
    }
    
    return dlm;
}
 
Example 27
Source Project: pumpernickel   Source File: SourceListUI.java    License: MIT License 5 votes vote down vote up
@Override
protected void paintCell(Graphics g0, int row, Rectangle rowBounds,
		ListCellRenderer cellRenderer, ListModel dataModel,
		ListSelectionModel selModel, int leadIndex) {

	Graphics2D g = (Graphics2D) g0;
	Object value = dataModel.getElementAt(row);
	boolean cellHasFocus = list.hasFocus() && (row == leadIndex);
	boolean isSelected = selModel.isSelectedIndex(row);

	paintBackground(g, rowBounds, value, row, isSelected, cellHasFocus);
	super.paintCell(g, row, rowBounds, cellRenderer, dataModel, selModel,
			leadIndex);
}
 
Example 28
Source Project: cakephp3-netbeans   Source File: GoToPopup.java    License: Apache License 2.0 5 votes vote down vote up
private ListModel<GoToItem> createListModel() {
    DefaultListModel<GoToItem> dlm = new DefaultListModel<>();

    for (GoToItem el : items) {
        dlm.addElement(el);
    }

    return dlm;
}
 
Example 29
Source Project: blog   Source File: ListModelHolder.java    License: Apache License 2.0 5 votes vote down vote up
public final void setModel(ListModel<E> listModel) {
	if (this.listModel != null) {
		removeListDataListeners(listModel, listDataListeners);
	}

	ListModel<E> oldModel = this.listModel;
	this.listModel = listModel;

	if (listModel != null) {
		addListDataListeners(listModel, listDataListeners);
	}

	propertyChangeSupport.firePropertyChange(PROPERTY_LIST_MODEL, oldModel, this.listModel);
}
 
Example 30
Source Project: netbeans   Source File: SearchPanel.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns the {@code ListModel} for the given libraries.
 * 
 * @param libraries libraries for which to return the model.
 * @return {@code ListModel} for the given libraries.
 */
private ListModel<Library> libraryListModelFor(Library[] libraries) {
    Arrays.sort(libraries, alphabeticalSortButton.isSelected() ?
            new AlphabeticLibraryComparator() :
            new PopularityLibraryComparator());
    DefaultListModel<Library> listModel = new DefaultListModel<>();
    for (Library library : libraries) {
        listModel.addElement(library);
    }
    return listModel;
}