下面列出了javax.swing.ListModel#getElementAt ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* This is called by <code>typingListener</code> when the user has typed a
* string. By default it will select the first item in the directory that
* starts with the same text.
*/
protected void stringTyped(String s) {
s = s.toLowerCase();
ListModel m = browser.getListModel();
int index = 0;
synchronized (m) {
while (index < m.getSize()) {
IOLocation loc = (IOLocation) m.getElementAt(index);
if (loc.getName().toLowerCase().startsWith(s)) {
browser.getSelectionModel().setSelection(loc);
return;
}
index++;
}
}
}
public Object getValueAt(int rowIndex, int columnIndex) {
Object columnValue = null;
ListModel<Person> listModel = personListModelHolder.getModel();
Person person = listModel.getElementAt(rowIndex);
Column column = getColumn(columnIndex);
switch (column) {
case FIRSTNAME:
columnValue = person.getFirstname();
break;
case LASTNAME:
columnValue = person.getLastname();
break;
default:
columnValue = getAddressObject(person, column);
break;
}
return columnValue;
}
/**
* Opens requested code generation dialog
* @param type Displayname of menu item
* @param editor Operator of editor window where should be menu opened
* @return true is item is found, false elsewhere
*/
public static boolean openDialog(String type, EditorOperator editor) {
new EventTool().waitNoEvent(1000);
editor.pushKey(KeyEvent.VK_INSERT, KeyEvent.ALT_DOWN_MASK);
JDialogOperator jdo = new JDialogOperator();
new EventTool().waitNoEvent(1000);
JListOperator list = new JListOperator(jdo);
ListModel lm = list.getModel();
for (int i = 0; i < lm.getSize(); i++) {
CodeGenerator cg = (CodeGenerator) lm.getElementAt(i);
if(cg.getDisplayName().equals(type)) {
list.setSelectedIndex(i);
jdo.pushKey(KeyEvent.VK_ENTER);
new EventTool().waitNoEvent(1000);
return true;
}
}
return false;
}
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);
}
}
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();
}
}
/**
* 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);
}
/**
* Return files currently displayed.
*
* @return an array of items from the file list.
*/
public File[] getFiles() {
waitPainted(-1);
ListModel<?> listModel = getFileList().getModel();
File[] result = new File[listModel.getSize()];
for (int i = 0; i < listModel.getSize(); i++) {
result[i] = (File) listModel.getElementAt(i);
}
return result;
}
private Set<String> getFormatterNames() {
Set<String> formatterNames = new HashSet<String>();
ListModel formattersModel = formattersList.getModel();
int n = formattersModel.getSize();
for (int i = 0; i < n; i++) {
VariablesFormatter vf = (VariablesFormatter) formattersModel.getElementAt(i);
formatterNames.add(vf.getName());
}
return formatterNames;
}
/**
* Saves the configured project debuggers to the database.
*/
private void saveDebuggers() {
try {
final ListModel<DebuggerTemplate> model = m_checkedList.getModel();
final List<DebuggerTemplate> oldDebuggers = m_project.getConfiguration().getDebuggers();
for (int i = 0; i < model.getSize(); ++i) {
final DebuggerTemplate debugger = model.getElementAt(i);
if (m_checkedList.isChecked(i) && !oldDebuggers.contains(debugger)) {
m_project.getConfiguration().addDebugger(debugger);
} else if (!m_checkedList.isChecked(i) && oldDebuggers.contains(debugger)) {
m_project.getConfiguration().removeDebugger(model.getElementAt(i));
}
}
} catch (final CouldntSaveDataException e) {
CUtilityFunctions.logException(e);
final String innerMessage = "E00173: " + "Could not save project debuggers";
final String innerDescription = CUtilityFunctions.createDescription(String.format(
"The new debuggers of the project '%s' could not be saved.",
m_project.getConfiguration().getName()),
new String[] {"There was a problem with the database connection."},
new String[] {"The project keeps its old debuggers."});
NaviErrorDialog.show(SwingUtilities.getWindowAncestor(CProjectNodeComponent.this),
innerMessage, innerDescription, e);
}
}
/**
* Check if Insertcode popup contains requested item
* @param editor Operator of editor window where should Insert Code should be caled
* @param items Expected items
* @return true if all requested item are pressent, to exact match use {@link #containsItems(org.netbeans.jellytools.EditorOperator, java.lang.String[]) containsItems}
*/
public static boolean checkItems(EditorOperator editor, String ... items) {
Set<String> expItems = new HashSet<String>(Arrays.asList(items));
editor.pushKey(KeyEvent.VK_INSERT, KeyEvent.ALT_DOWN_MASK);
JDialogOperator jdo = new JDialogOperator();
JListOperator list = new JListOperator(jdo);
ListModel lm = list.getModel();
for (int i = 0; i < lm.getSize(); i++) {
CodeGenerator cg = (CodeGenerator) lm.getElementAt(i);
expItems.remove(cg.getDisplayName());
}
if(!expItems.isEmpty()) return false;
return true;
}
private void invokeTemplateAsHint(EditorOperator editor, final String description) {
final String blockTemplatePrefix = "<html>Surround with ";
new EventTool().waitNoEvent(500);
editor.pressKey(KeyEvent.VK_ENTER, KeyEvent.ALT_DOWN_MASK);
new EventTool().waitNoEvent(500);
JListOperator jlo = new JListOperator(MainWindowOperator.getDefault());
ListModel model = jlo.getModel();
int i;
for (i = 0; i < model.getSize(); i++) {
Object item = model.getElementAt(i);
String hint = "n/a";
if (item instanceof SurroundWithFix) {
hint = ((SurroundWithFix) item).getText();
}
if (hint.startsWith(blockTemplatePrefix + description)) {
System.out.println("Found at "+i+" position: "+hint);
break;
}
}
if (i == model.getSize()) {
fail("Template not found in the hint popup");
}
new EventTool().waitNoEvent(2000);
jlo.selectItem(i);
new EventTool().waitNoEvent(500);
}
/**
* 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());
}
/**
* Updates the order of the libraries/packages in the list.
*/
void updateLibraryOrder() {
Library selected = librariesList.getSelectedValue();
ListModel<Library> model = librariesList.getModel();
Library[] libraries = new Library[model.getSize()];
for (int i=0; i<model.getSize(); i++) {
libraries[i] = model.getElementAt(i);
}
librariesList.setModel(libraryListModelFor(libraries));
if (selected != null) {
librariesList.setSelectedValue(selected, true);
}
}
public static void useHint(final EditorOperator editor, final int lineNumber, String hintPrefix) throws InterruptedException {
Object annots = new Waiter(new Waitable() {
public Object actionProduced(Object arg0) {
Object[] annotations = editor.getAnnotations(lineNumber);
if (annotations.length == 0) {
return null;
} else {
return annotations;
}
}
public String getDescription() {
return "Waiting for annotations for current line";
}
}).waitAction(null);
editor.pressKey(KeyEvent.VK_ENTER, KeyEvent.ALT_DOWN_MASK);
JListOperator jlo = new JListOperator(MainWindowOperator.getDefault());
int index = -1;
ListModel model = jlo.getModel();
for (int i = 0; i < model.getSize(); i++) {
Object element = model.getElementAt(i);
String desc = getText(element);
if (desc.startsWith(hintPrefix)) {
index = i;
}
}
assertTrue("Requested hint not found", index != -1);
jlo.selectItem(index);
jlo.pushKey(KeyEvent.VK_ENTER);
}
public ArrayList<String> getGcmAbstractions()
{
ArrayList<String> gcmAbsList = new ArrayList<String>();
ListModel<String> preAbsList = preAbs.getModel();
for (int i = 0; i < preAbsList.getSize(); i++)
{
String abstractionOption = preAbsList.getElementAt(i);
if (abstractionOption.equals("complex-formation-and-sequestering-abstraction") || abstractionOption.equals("operator-site-reduction-abstraction"))
{
gcmAbsList.add(abstractionOption);
}
}
return gcmAbsList;
}
public static void selectTestProject(final BugzillaQuery q) {
QueryPanel qp = (QueryPanel) q.getController().getComponent(QueryMode.EDIT);
ListModel model = qp.productList.getModel();
for (int i = 0; i < model.getSize(); i++) {
QueryParameter.ParameterValue pv = (ParameterValue) model.getElementAt(i);
if (pv.getValue().equals(TEST_PROJECT)) {
qp.productList.setSelectedIndex(i);
break;
}
}
}
@Override
protected void synchronizeDirectoryContents() {
List<IOLocation> v = new ArrayList<IOLocation>();
ListModel model = browser.getListModel();
synchronized (model) {
for (int a = 0; a < model.getSize(); a++) {
IOLocation loc = (IOLocation) model.getElementAt(a);
if (loc.isHidden() == false)
v.add(loc);
}
}
Collections.sort(v, getLocationComparator());
synchronized (threadsafeListModel) {
threadsafeListModel.setAll(v);
}
// synchronize the selection
if (adjustingModels > 0)
return;
adjustingModels++;
try {
IOLocation[] obj = browser.getSelectionModel().getSelection();
List<Integer> ints = new ArrayList<Integer>();
Rectangle visibleBounds = null;
int[] indices;
synchronized (threadsafeListModel) {
for (int a = 0; a < obj.length; a++) {
int k = threadsafeListModel.indexOf(obj[a]);
if (k != -1) {
ints.add(new Integer(k));
}
}
indices = new int[ints.size()];
for (int a = 0; a < ints.size(); a++) {
indices[a] = (ints.get(a)).intValue();
}
list.setSelectedIndices(indices);
if (indices.length > 0) {
visibleBounds = list.getCellBounds(indices[0], indices[0]);
}
}
if (visibleBounds != null) {
try {
list.scrollRectToVisible(visibleBounds);
} catch (RuntimeException e) {
System.err.println("indices[0] = " + indices[0]
+ " out of:");
for (int a = 0; a < list.getModel().getSize(); a++) {
System.err.println("\tlist[a] = "
+ list.getModel().getElementAt(a));
}
throw e;
}
}
} finally {
adjustingModels--;
}
}
private boolean selectMessage(MessageType xmlMessageType)
{
boolean isRecognizedMessage = false;
ListModel<Message> listModel = messagesList.getModel();
for (int i = 0; i < listModel.getSize(); i++)
{
Message message = listModel.getElementAt(i);
if (message.getMsgType().equals(xmlMessageType.getMsgType()))
{
messagesList.setSelectedIndex(i);
if (xmlMessageType.isIsRequiredOnly())
{
requiredCheckBox.setSelected(true);
} else
{
requiredCheckBox.setSelected(false);
}
if (xmlMessageType.getHeader() != null
&& xmlMessageType.getHeader().getField() != null
&& xmlMessageType.getHeader().getField().isEmpty())
{
modifyHeaderCheckBox.setSelected(true);
} else
{
modifyHeaderCheckBox.setSelected(false);
}
if (xmlMessageType.getTrailer() != null
&& xmlMessageType.getTrailer().getField() != null
&& xmlMessageType.getTrailer().getField().isEmpty())
{
modifyTrailerCheckBox.setSelected(true);
} else
{
modifyTrailerCheckBox.setSelected(false);
}
isRecognizedMessage = true;
}
}
if (!isRecognizedMessage)
{
logger.error("Unrecognized message: ", xmlMessageType.getName()
+ " (" + xmlMessageType.getMsgType() + ")");
JOptionPane.showMessageDialog(
this,
"Unable to import message from unrecognized message: "
+ xmlMessageType.getName() + " ("
+ xmlMessageType.getMsgType() + ")", "Error",
JOptionPane.ERROR_MESSAGE);
return false;
}
return true;
}
@Override
protected void paintCell(Graphics g, int row, Rectangle rowBounds,
ListCellRenderer cellRenderer, ListModel dataModel,
ListSelectionModel selModel, int leadIndex) {
super.paintCell(g, row, rowBounds, cellRenderer, dataModel, selModel,
leadIndex);
Object value = dataModel.getElementAt(row);
boolean cellHasFocus = list.hasFocus() && (row == leadIndex);
boolean isSelected = selModel.isSelectedIndex(row);
ListDecoration[] decorations = getDecorations(list);
for (int a = 0; a < decorations.length; a++) {
if (decorations[a].isVisible(list, value, row, isSelected,
cellHasFocus)) {
Point p = decorations[a].getLocation(list, value, row,
isSelected, cellHasFocus);
Icon icon = decorations[a].getIcon(list, value, row,
isSelected, cellHasFocus, false, false);
// we assume rollover/pressed icons are same dimensions as
// default icon
Rectangle iconBounds = new Rectangle(rowBounds.x + p.x,
rowBounds.y + p.y, icon.getIconWidth(),
icon.getIconHeight());
if (armedDecoration != null && armedDecoration.value == value
&& armedDecoration.decoration == decorations[a]) {
icon = decorations[a].getIcon(list, value, row, isSelected,
cellHasFocus, false, true);
} else if (iconBounds.contains(mouseX, mouseY)) {
icon = decorations[a].getIcon(list, value, row, isSelected,
cellHasFocus, true, false);
}
Graphics g2 = g.create();
try {
icon.paintIcon(list, g2, iconBounds.x, iconBounds.y);
} finally {
g2.dispose();
}
}
}
}
/**
* Returns true if the given model is not <code>null</code> and contains
* only the given value.
*/
public static boolean hasOnlyValue(final ListModel model, final Object value) {
return model != null && model.getSize() == 1 && model.getElementAt(0) == value;
}