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

The following examples show how to use javax.swing.JList#getModel() . 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: UnitType.java    From freecol with 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 2
Source File: TaskPanel.java    From netbeans with 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 3
Source File: RunAnalysisPanel.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Messages({"LBL_RunAllAnalyzers=All Analyzers", "# {0} - the analyzer that should be run", "LBL_RunAnalyzer={0}"})
@Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
    if (value == null) {
        value = Bundle.LBL_RunAllAnalyzers();
    } else if (value instanceof AnalyzerFactory) {
        value = Bundle.LBL_RunAnalyzer(SPIAccessor.ACCESSOR.getAnalyzerDisplayName((AnalyzerFactory) value));
    } else if (value instanceof Configuration) {
        value = ((Configuration) value).getDisplayName();
    } else if (value instanceof String) {
        setFont(getFont().deriveFont(Font.ITALIC));
        setText((String) value);
        setEnabled(false);
        setBackground(list.getBackground());
        setForeground(UIManager.getColor("Label.disabledForeground"));

        return this;
    }

    if (index == list.getModel().getSize()-5 && list.getModel() instanceof ConfigurationsComboModel && ((ConfigurationsComboModel) list.getModel()).canModify()) {
        setBorder(new Separator(list.getForeground()));
    } else {
        setBorder(null);
    }

    return super.getListCellRendererComponent(list, (indent ? "  " : "") + value, index, isSelected, cellHasFocus);
}
 
Example 4
Source File: CodeCompletionPanel.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void updateExcluder(JList list) {
    DefaultListModel model = (DefaultListModel) list.getModel();
    StringBuilder builder = new StringBuilder();
    for (int i = 0 ; i < model.size() ; i++) {
        String entry = (String) model.getElementAt(i);
        if (builder.length() > 0) {
            builder.append(","); //NOI18N
        }
        builder.append(entry);
    }
    String pref;
    if (list == javaCompletionExcludeJlist)
        pref = JAVA_COMPLETION_BLACKLIST;
    else if (list == javaCompletionIncludeJlist)
        pref = JAVA_COMPLETION_WHITELIST;
    else
        throw new RuntimeException(list.getName());

    preferences.put(pref, builder.toString());
}
 
Example 5
Source File: WebSocketUiHelper.java    From zap-extensions with 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 6
Source File: DisassembledViewPluginTest.java    From ghidra with 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 7
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 8
Source File: FolderList.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public void exportDone(JComponent comp, Transferable trans, int action) {
    if (action == MOVE) {
        final JList from = (JList) comp;
        final DefaultListModel model = (DefaultListModel) from.getModel();
        for (int i=indices.length-1; i>=0; i--) {
            model.removeElementAt(indices[i]);
        }
    }
}
 
Example 9
Source File: UseSpecificCatchCustomizer.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void initList(JList l, String val) {
    StringTokenizer tukac = new StringTokenizer(val, ", ");
    DefaultListModel m = (DefaultListModel)l.getModel();
    while (tukac.hasMoreTokens()) {
        String s = tukac.nextToken();
        if (s.isEmpty()) {
            continue;
        }
        m.addElement(s);
    }
    prefs.put(UseSpecificCatch.OPTION_EXCEPTION_LIST, val);
}
 
Example 10
Source File: UnitType.java    From freecol with GNU General Public License v2.0 5 votes vote down vote up
@Override
public int getMinimumIndex(Colony colony, JList<BuildableType> buildQueueList, int UNABLE_TO_BUILD) {
    ListModel<BuildableType> buildQueue = buildQueueList.getModel();
    if (colony.canBuild(this)) return 0;
    for (int index = 0; index < buildQueue.getSize(); index++) {
        if (buildQueue.getElementAt(index).hasAbility(Ability.BUILD, this)) return index + 1;
    }
    return UNABLE_TO_BUILD;
}
 
Example 11
Source File: ShowToolSettingsPanel.java    From jeveassets with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public boolean importData(TransferSupport info) {
	TransferHandler.DropLocation tdl = info.getDropLocation();
	if (!canImport(info) || !(tdl instanceof JList.DropLocation)) {
		return false;
	}

	JList.DropLocation dl = (JList.DropLocation) tdl;
	JList<?> target = (JList) info.getComponent();
	DefaultListModel<Object> listModel = (DefaultListModel) target.getModel();
	int max = listModel.getSize();
	int index = dl.getIndex();
	index = index < 0 ? max : index; // If it is out of range, it is appended to the end
	index = Math.min(index, max);

	addIndex = index;

	try {
		Object[] values = (Object[]) info.getTransferable().getTransferData(localObjectFlavor);
		for (Object value : values) {
			int idx = index++;
			listModel.add(idx, value);
			target.addSelectionInterval(idx, idx);
		}
		addCount = values.length;
		return true;
	} catch (UnsupportedFlavorException | IOException ex) {
		LOG.error(ex.getMessage(), ex);
		return false;
	}
}
 
Example 12
Source File: CodeCompletionPanel.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void javaCompletionExcluderRemoveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_javaCompletionExcluderRemoveButtonActionPerformed
    JList list = getSelectedExcluderList();
    int[] rows = list.getSelectedIndices();
    DefaultListModel model = (DefaultListModel) list.getModel();
    // remove rows in descending order: row numbers change when a row is removed
    for (int row = rows.length - 1; row >= 0; row--) {
        model.remove(rows[row]);
    }
    updateExcluder(list);
}
 
Example 13
Source File: ListTransferHandler.java    From marathonv5 with Apache License 2.0 5 votes vote down vote up
@Override
public boolean importData(TransferHandler.TransferSupport info) {
    if (!info.isDrop()) {
        return false;
    }

    JList list = (JList) info.getComponent();
    DefaultListModel listModel = (DefaultListModel) list.getModel();
    JList.DropLocation dl = (JList.DropLocation) info.getDropLocation();
    int index = dl.getIndex();
    boolean insert = dl.isInsert();

    // 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;
    }

    // Perform the actual import.
    if (insert) {
        listModel.add(index, data);
    } else {
        listModel.set(index, data);
    }
    return true;
}
 
Example 14
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 15
Source File: EditCustomCategoryDialog.java    From tda with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void moveFilter(JList fromList, JList toList, int selectedItem) {
    Filter filter = (Filter) ((DefaultListModel) fromList.getModel()).getElementAt(selectedItem);
    ((DefaultListModel) fromList.getModel()).removeElementAt(selectedItem);
    
    DefaultListModel dlm = ((DefaultListModel) toList.getModel());

    dlm.ensureCapacity(dlm.getSize() + 1);
    dlm.addElement(filter);
    toList.ensureIndexIsVisible(dlm.getSize());
}
 
Example 16
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 17
Source File: TradeRouteInputPanel.java    From freecol with GNU General Public License v2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected Transferable createTransferable(JComponent c) {
    JList list = (JList)c;
    final DefaultListModel model = (DefaultListModel)list.getModel();
    int[] indicies = list.getSelectedIndices();
    List<TradeRouteStop> stops = new ArrayList<>(indicies.length);
    for (int i : indicies) stops.add(i, (TradeRouteStop)model.get(i));
    return new StopListTransferable(stops);
}
 
Example 18
Source File: ListUtils.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
public static <T, R> List<R> getAllItems(JList<T> jlist, IntFunction<R> mapFunc) {
  ListModel<T> model = jlist.getModel();
  return IntStream.range(0, model.getSize()).mapToObj(mapFunc).collect(Collectors.toList());
}
 
Example 19
Source File: BuildingType.java    From freecol with GNU General Public License v2.0 4 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;
    }

    BuildingType upgradesFrom = this.getUpgradesFrom();
    BuildingType upgradesTo = this.getUpgradesTo();
    // does not depend on nothing, but still cannot be built
    if (!canBuild && upgradesFrom == null) {
        return UNABLE_TO_BUILD;
    }

    // if can be built and does not have any upgrade,
    // then it can be built at any time
    if (canBuild && upgradesTo == null) {
        return buildQueueLastPos;
    }

    // if can be built, does not depend on anything, mark
    // upgrades from as found
    boolean foundUpgradesFrom = canBuild;
    for (int index = 0; index < buildQueue.getSize(); index++) {
        BuildableType toBuild = buildQueue.getElementAt(index);

        if (toBuild == this) continue;

        if (!canBuild && !foundUpgradesFrom
                && upgradesFrom.equals(toBuild)) {
            foundUpgradesFrom = true;
            // nothing else to upgrade this building to
            if (upgradesTo == null) return buildQueueLastPos;
        }
        // found a building it upgrades to, cannot go to or
        // beyond this position
        if (foundUpgradesFrom && upgradesTo != null
                && upgradesTo.equals(toBuild)) return index;

        // Don't go past a unit this building can build.
        if (this.hasAbility(Ability.BUILD, toBuild)) {
            return index;
        }
    }
    return buildQueueLastPos;
}
 
Example 20
Source File: ListUtils.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
public static <T> List<T> getAllItems(JList<T> jlist) {
  ListModel<T> model = jlist.getModel();
  return getAllItems(jlist, model::getElementAt);
}