I have an ArrayList which holds employee record details from data inputted into JTextFields. I have displayed this with a showMessageDialog box to confirm that they are being added to the list correctly.
The employees are created and added to the list correctly but how do I cycle through the ArrayList one record at a time and have the information displayed in the JTextFields?
Edited as below:
I don't think I have asked the question properly. I have a button that enables me to show the contents of the first element of my array list to the GUI. See below:
nField.setText(nameList.get(0).getName());
bField.setText(nameList.get(0).getBirth());
jField.setText(nameList.get(0).getID());
What I need is something to show the next element.
I have a list iterator that I am trying to use but I simply can’t get it to work.
I have tried this but it results in the last element being shown:
for (int i = 0; i < nameList.size(); i++) {
nameList.get(i);
nField.setText(nameList.get(i).getName());
bField.setText(nameList.get(i).getBirth());
jfield.setText(nameList.get(i).getID()); }
There are different options, but the short of it is, you'll have to tie your employee record to the JTextField somehow. One way to do this is by creating a simple object to hold the relation:
public class EmployeeRecordToJTextfield {
private EmployeeRecord employeeRecord;
private JTextField jTextField;
public EmployeeRecordToJTextfield(EmployeeRecord employeeRecord, JTextField jTextField) {
this.employeeRecord = employeeRecord;
this.jTextField = jTextField;
}
public EmployeeRecord getEmployeeRecord() {
return employeeRecord;
}
public JTextField getJTextField() {
return jTextField;
}
}
Instead of the EmployeeRecord, you stick instances of this class in the list:
List<EmployeeRecordToJTextfield> list = new ArrayList<>();
list.add(new EmployeeRecordToJTextfield(employeeRecord, jTextField));
When you iterate over this list, you can transfer the data you choose:
for (EmployeeRecordToJTextfield e : list) {
JTextField textField = e.getJTextField();
EmployeeRecord record = e.getEmployeeRecord();
textField.setText(record.getName());
}
Another option, maybe simpler, is by converting your list to a map and map EmployeeRecords to their JTextField.
Update based on the Question update
I hope I now understand what you're asking, but if so, I'd just do this:
Store the index of the 'current' shown item in a variable or hidden GUI field.
private int currentIndex = 0; // Start with the first item.
When you want to show the next item (perhaps through a Next or Previous button), get the next value. Compensate for list length:
int nextIndex = currentIndex+1;
if (nextIndex >= nameList.size()) nextIndex = 0;
if (nextIndex < 0) nextIndex = nameList.size()-1;
Now you can use nextIndex to fetch the correct entry from your list:
nField.setText(nameList.get(nextIndex).getName());
bField.setText(nameList.get(nextIndex).getBirth());
jfield.setText(nameList.get(nextIndex).getID());
And don't forget to update the currentIndex:
this.currentIndex = nextIndex;
Use for loop:
for(JTextField a : your_list){
do_something();
}
Related
I have an ArrayList with lots of objects. I want to be able to add any objects into a choice of 3 different LinkedLists. A user input will select which item to add to which LinkedList by typing the index they wish to be added. This is the kind of thing i'm after, but i just can't get it to work:
public void addToRepository(int indx, int r) {
if (r == 1){ //checks to see if chosen repository 1
for (int i=0; i < itemList.size(); i++) {
i = indx;
} // ignore this it was just me playing around to see if i'd be able to get the index this way..
repo1.add(itemList.get(indx)); //adds item from "itemList" with the index that
the user input has given
//other if statements
}
}
I'm not sure this is the correct idea but it gives error "Item cannot be converted to String". If not, how can i go about doing this?
So you have
ArrayList<Item> itemList = new ArrayList<Item>();
and you are trying to do -
repo1.add(itemList.get(indx));
As per the Exception you are getting it looks like repo1 has String data. You can do one of the following things -
Use repo1.add(itemList.get(indx).toString()); OR
Change repo1 generics to include Item data instead of String
I need to implement "paging" for my application's FlexTable widget:
Here is my initial code where it renders a Product into a 3 column cell:
public void renderProducts(Map<Long, Product> mp) {
int i = 0;
int j = 0;
Iterator it = mp.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
Product product = (Product) pairs.getValue();
ProductWidget pw = productInstance.get();
pw.setTitle(product.getName());
pw.setImageUrl(product.getImageUrl());
pw.setContent(product.getInfo());
pw.setUrl(product.getUrl()); // "More" button anchor
List<String> feats = product.getFeatures();
for (String f : feats){
pw.addFeature(f);
}
flextable.setWidget(i, j, pw);
j++;
if (j == 3){
i++;
j = 0;
}
it.remove(); // avoids a ConcurrentModificationException
}
}
Need to do paging in N pages for this. My initial idea is to split the Map into a List of Map...
I mean, is there any "data source" for FlexTable?
If you really need to use the FlexTable and provide paging you had better do it using a cell table so older question. The simple pager implements all the functionality you want either way.
If you want to go with the FlexTable you have to provide with your own implementation of a pager. This can be done in varous ways, with next and previous button or Labels adding the on click handler and doing the iterations.
The map is also not the way to go as the items are not ordered in any way. I would add all the items to a List and use said list as my data source.
You also need a way to save the current page and the items/page ( maybe a static variable if you want it saved even after the page has changed )
I am using a hashmap to populate a jtable. The user selects a row(s) and clicks a edit button. I am taking the value from the hashmap and placing it in a textarea. The user can make changes and then clicks another button. I have the new value and the key, but I am not sure how to write the changed value back to the right key in the hashmap.
THis is where I am writing the data out to the textarea
private void outputSelection() {
StringBuffer csb = new StringBuffer();
String s = "";
int[] row = selectTable.getSelectedRows();
for(int i = row.length-1; i >= 0; i--){
String check = (String) EdiMapTableModel.getMapInstance().getValueAt(i, EdiMapTableModel.getMapInstance().COMMENT_COL);
if (!isNullOrEmpty(check)) {
if (csb.length() > 0) {
csb.append("\n");
}
csb.append(check);
}
}
s = csb.toString();
csb.setLength(0);
output.append(s);
}
This is where I am trying to put the value back
private void inputSelection() {
String s = output.getText();
int[] row = selectTable.getSelectedRows();
for(int i = row.length-1; i >= 0; i--){
TCComponentItemRevision check = (TCComponentItemRevision) EdiMapTableModel.getMapInstance().getValueAt(i, EdiMapTableModel.getMapInstance().ITEMID_COL);
EdiMapTableModel.getMapInstance().commentBackMap(check, s);
repaint();
}
}
This is where I am trying to put it back in the map
public void commentBackMap(int row, TCComponentItemRevision id, String comment) {
if(model.containsKey(id)) {
model.put(id, comment);
}
fireTableDataChanged();
}// end commentBackMap()
I know containsKey is not right above. id is the key value
Do I need to iterate through the hashmap looking for a match? Don't know if it matters but it is a linkedhashmap instead of a hashmap
According to the HashMap#put documentation:
Associates the specified value with the specified key in this map. If
the map previously contained a mapping for the key, the old value is
replaced.
So all you have to do is call put with the same key and the new value, it will do the replacement for you.
This also applies to LinkedHashMap because it inherits the put method from HashMap.
If you want to maintain the location of your map entry, you can't put it again since that's going to move it to the end of the LinkedHashMap. You'll need a holder object, say an Object[1], where you'll replace its member without putting the map entry again.
Or maybe reevaluate your choice of LinkedHashMap.
I have my method which sorts all the movies in the array (dArray) of class dvd. now i need to sort available movies (setAvailable == true) ONLY. the array is dynamically filled in by customers entering movies from the menu. my code currently searches through the array and sorts all movies from A to B but now i want it to search and sort only the movies whereby d.setAvailable(true)... Thanks for your help. much appreciated
here is the sorted list of all the movies in the array:
if(e.getSource() == sortMovBtn)
{
if(dArray[0]==null)
{
JOptionPane.showMessageDialog(null,"No movies, please enter\na movie from the main menu","Error",JOptionPane.ERROR_MESSAGE);
}
else
{
BtnPanel.setVisible(false);
imgPnl.setVisible(false);
btnBackDvd.setVisible(true);
txtAreaSortDvd.setVisible(true);
sortDvdPnl.setVisible(true);
Dvd tmp;
for (int i = 0; i < manyDvd; i++)
{
for (int j = 0; j < (manyDvd - 1 - i); j++)
{
if (dArray[j].getTitle().compareTo(dArray[j+1].getTitle()) > 0)
{
tmp = dArray[j];
dArray[j] = dArray[j+1];
dArray[j+1] = tmp;
}
}
}
a = "";
for (int k = 0; k <manyDvd /*dArray.length*/; k++)
a += (dArray[k]);
txtAreaSortDvd.setText(a);
txtAreaSortDvd.setVisible(true);
txtAreaSortDvd.setEditable(false);
//Set font of text area
txtAreaSortDvd.setFont(new Font("Arial", Font.BOLD, 12));
//Initialize JScrollPane
JScrollPane pane1 = new JScrollPane(txtAreaSortDvd);
//Enable user to use wheel on mouse to scroll
pane1.setWheelScrollingEnabled(true);
//Set the scrollbar to always show
pane1.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
//Add ScrollPane to Panel
sortDvdPnl.add(pane1);
//Add panel to frame
add(sortDvdPnl);
}
}
First, you shouldn't have code to work with your model (data) mixed in with UI code.
Second, you should not be sorting the data on the UI thread. Do the work on a background worker thread.
Third, you should not be coding up the sort yourself, especially not like that. Your sort is O(n^2). There are good options for sorting in java.util.Arrays for arrays or java.util.Collections for the collection classes.
There are two basic ways to go about sorting just the items that meet a certain criterion. You could sort the entire data set with a custom Comparator, matching first by the criterion and second by the rest of your sort criteria. Then your results would be at the start of the data, and you would only show the results until the first item that does not meet the criterion.
This has the advantage that it uses no extra space beyond what is already required to store your data.
A cleaner way would be to make a copy of just that portion of the data that meets the criterion, and then sort that. It would also be much easier to work with if the data was in a List instead of an array, since you would not need make two passes over the data: one to find out how many items match the criterion, and one to filter out the matching items. (In between, you would allocate an array to hold them.)
Suppose your data was in a List. You could get the available movies like this:
public List<Movie> getAvailable(List<Movie> movies) {
List<Movie> avail = new ArrayList<Movie>();
for (Movie movie : movies) {
if (movie.isAvailable()) {
avail.add(movie);
}
}
return avail;
}
You could then sort these movies (in their natural sort order) like this:
List<Movie> availOnly = getAvailable(movies);
Collections.sort(availOnly);
P.S. In Java 8 you will be able to do something like:
Iterable<Movie> avail = movies.filter(Movie::isAvailable).sorted();
use comparator http://docs.oracle.com/javase/6/docs/api/java/util/Comparator.html
Vector<String> totalProducts = Products.getProductNames();
Vector<String> selectedProducts = Products.getSelectedProductNames();
The selectedProducts vector is a subvector of totalProducts (meaning that selectedProducts contains one, more or all of the elements from totalProducts). What I want is to combine these two vectors and make a single JList, which contains all the elements from totalProducts, and with the elements of selectedProducts already selected.
What I tried:
Vector<Integer> indices = new Vector<Integer>();
JList prdList = new JList(totalProducts);
for(int i = 0; i < totalProducts.size(); i++)
{
for(String name : selectedProducts)
{
if(totalProducts.contains(name)) indices.add(i);
}
}
Object [] objIndices = indices.toArray();
//... Cast from Object [] to int [] ....
prdList.setSelectedIndices(intIndices);
...but this selects all the elements in the final JList.
Previously I tried:
JList prdList = new JList(totalProducts);
for(String tName : totalProducts)
{
for(String sName : selectedProducts)
{
if(totalProducts.contains(sName)) prdList.setSelectedValue(sName, false);
}
}
...but this one selected only the last element from the selectedProducts.
Can you please help me to do it right?
Your attempt that selects all items does so because you're iterating over each item, and if any item from the selectedProducts list is in the total list, adds the iteration item's index to the final selection list. Try changing your loop to something like this:
for(int i = 0; i < totalProducts.size(); i++)
{
String name = totalProducts.get(i);
if(selectedProducts.contains(name)) indices.add(i);
}
in debugging your first attempt (which looks like it should work, what was the contents of your intIndices array? because that looks like it should work, presuming your array conversion works.
however, since selectedproducts is guaranteed to be less items than total, you might want to iterate over that instead?
List<Integer> indices = new ArrayList<Integer>(selectedProducts.size());
for(String name : selectedProducts)
{
int index = totalProducts.indexOf(name);
if (index != -1)
indices.add(index);
}
although, since indexOf is a linear search through a list, it probably doesn't make much of a difference either way.
as for your second attempt, the ListSelectionModel has methods for adding a selected index (addSelectionInterval(int index0, int index1))
, you're using the one that sets (overwrites) the selection.
see http://download.oracle.com/javase/6/docs/api/javax/swing/ListSelectionModel.html
aside: you might want to use List<> instead of Vector<>, as vector has a lot of unecessary synchronization overhead. Unless you need the synchronization....
edit fixed copy+paste of add(i) with add(index)