How to access a particular element in JLIST? - java

I am trying to push a selected value at index 'a' to index 'a+1'.
But if index 'a+1' is not empty, I have to swap the two values. For this, I do not know how to obtain the value at index 'a+1'. It is not selected. The JList API does not support random access.
How do I implement this ?
Thanks.

To access the elements in a JList you need to get hold of its ListModel.
The model has a getElementAt(int) method.
item = myJList.getModel().getElementAt(a+1);

Related

Get the ArrayList index of an element after using a row filter on a JTable

I have an ArrayList containing multiple elements, each element contains the next fields:
Name
Address
Age
I have a JTable to show the information contained in the ArrayList.
I have a TableRowSorter to filter the information, according to a certain field.
Let´s say after filtering I get only one element, therefore the JTable has now one row. How can I get the index of that element in the original ArrayList? Do I have to implement one more field kind of "ID"?
int viewIndex = 0; // the index in the table of the unique filtered row.
int modelIndex = table.convertRowIndexToModel();
modelIndex is the index of the row in the list backing the table model.

JList - get number of selected elements in multi-select list

How do i get the number of selected elements from my jlist? So that i can create an int[] array and add the selected indices to this array.
JList.getSelectedIndices().length would give you the array length :) Refer Javadocs mate

delete and move elements in a table : java

private JEditorPane textArea[]= new JEditorPane[maxTabs];
I've got this table,I want to delete some elements and move the others, for example if I delete the second element, the third will be instead of the second and so on.
Depending on scenario you are interested (we remove for example element at position 1)
1) If elements should be shifted to left and last element should be set to 0 or null depending on type of array like
before [0,1,2,3,4]
after [0,2,3,4,0]
you can use
System.arraycopy(textArea, index+1, textArea, index, textArea.length-index-1);
array[array.length-1]=null;
2) when you want to replace old array with new one that wont contain selected element like
before [0,1,2,3,4]
after [0,2,3,4] //we removed element at position 1 (new array is smaller)
you can try something like this
List<JEditorPane> listCopy = new ArrayList<JEditorPane>(
Arrays.asList(textArea));
listCopy.remove(index);
textArea = listCopy.toArray(new JEditorPane[listCopy.size()]);
You can use System.arraycopy() to move chunks of arrays around: see https://stackoverflow.com/a/5536023/150001
If you can, though, consider using a Collection class like java.util.LinkedList, which is much better suited to removing and reordering elements. If you still need an array when you're done with your deletions/moves (maybe the API you're working with requires it), you can use the toArray() method.

Adding elements into ArrayList at position larger than the current size

Currently I'm using an ArrayList to store a list of elements, whereby I will need to insert new elements at specific positions. There is a need for me to enter elements at a position larger than the current size. For e.g:
ArrayList<String> arr = new ArrayList<String>();
arr.add(3,"hi");
Now I already know there will be an OutOfBoundsException. Is there another way or another object where I can do this while still keeping the order? This is because I have methods that finds elements based on their index. For e.g.:
ArrayList<String> arr = new ArrayList<String>();
arr.add("hi");
arr.add(0,"hello");
I would expect to find "hi" at index 1 instead of index 0 now.
So in summary, short of manually inserting null into the elements in-between, is there any way to satisfy these two requirements:
Insert elements into position larger than current size
Push existing elements to the right when I insert elements in the middle of the list
I've looked at Java ArrayList add item outside current size, as well as HashMap, but HashMap doesn't satisfy my second criteria. Any help would be greatly appreciated.
P.S. Performance is not really an issue right now.
UPDATE: There have been some questions on why I have these particular requirements, it is because I'm working on operational transformation, where I'm inserting a set of operations into, say, my list (a math formula). Each operation contains a string. As I insert/delete strings into my list, I will dynamically update the unapplied operations (if necessary) through the tracking of each operation that has already been applied. My current solution now is to use a subclass of ArrayList and override some of the methods. I would certainly like to know if there is a more elegant way of doing so though.
Your requirements are contradictory:
... I will need to insert new elements at specific positions.
There is a need for me to enter elements at a position larger than the current size.
These imply that positions are stable; i.e. that an element at a given position remains at that position.
I would expect to find "hi" at index 1 instead of index 0 now.
This states that positions are not stable under some circumstances.
You really need to make up your mind which alternative you need.
If you must have stable positions, use a TreeMap or HashMap. (A TreeMap allows you to iterate the keys in order, but at the cost of more expensive insertion and lookup ... for a large collection.) If necessary, use a "position" key type that allows you to "always" generate a new key that goes between any existing pair of keys.
If you don't have to have stable positions, use an ArrayList, and deal with the case where you have to insert beyond the end position using append.
I fail to see how it is sensible for positions to be stable if you insert beyond the end, and allow instability if you insert in the middle. (Besides, the latter is going to make the former unstable eventually ...)
even you can use TreeMap for maintaining order of keys.
First and foremost, I would say use Map instead of List. I guess your problem can be solved in better way if you use Map. But in any case if you really want to do this with Arraylist
ArrayList<String> a = new ArrayList<String>(); //Create empty list
a.addAll(Arrays.asList( new String[100])); // add n number of strings, actually null . here n is 100, but you will have to decide the ideal value of this, depending upon your requirement.
a.add(7,"hello");
a.add(2,"hi");
a.add(1,"hi2");
Use Vector class to solve this issue.
Vector vector = new Vector();
vector.setSize(100);
vector.set(98, "a");
When "setSize" is set to 100 then all 100 elements gets initialized with null values.
For those who are still dealing with this, you may do it like this.
Object[] array= new Object[10];
array[0]="1";
array[3]= "3";
array[2]="2";
array[7]="7";
List<Object> list= Arrays.asList(array);
But the thing is you need to identify the total size first, this should be just a comment but I do not have much reputation to do that.

Strategy for detecting an object in JTable row?

Here's the thing: a sortable JTable backed by JTableModel with an array of objects that populate rows (one object = one row). Need to delete rows.
Without sorting, deleting an object is simple: get selected row index, delete array object under the same index. With sorting, though, row indexes mess up in a sense that they no longer match backing array object indexes. What's the proper way to overcome this?
Oscar was almost right, here's how it should be done:
int selectedRow = table.getSelectedRow();
tableModel.removeRow(table.convertRowIndexToModel(selectedRow));
I think ( not quite sure ) there is a method like "modelToView" which returns the actual index in the model a view index represents.
So, for instance you have A,B,C,D and then you sort desc. D,C,B,A this method would return 0 for view index 3 ( A )
I think this was on JXTable which supports sorting or in JTable in Java 6.
If you have build this sorting your self, consider adding this method.

Categories