How this API can get items of a JList (String) - java

I have a JList with a few items, Then I got an API that need to get the selected item and use it to provide some information about that item. My problem is that the type of the JList is String and the type of my API is obviously something different. Lets say LocationAPI. So the API gets index only from its own type and not other ones. I am looking for a solution to convert the selected item (String) to something suitable for the API. Here is a simple example of the API.
LinkedList<LocationAPI> stations = FetchWeatherForecast.findWeatherStationsNearTo("cityName");
for (LocationAPI station : stations) { System.out.println(station); }
// Assume the first match on the list is correct
LocationAPI firstMatch = stations.getFirst();
List<ForecastForOneDay> forecast = FetchWeatherForecast.getWeatherForecast(firstMatch);
So it is a simple example of how the API works, But Instead of 'firstMatch' and 'Station' I have to use my own items and lists. I got the Item and list, but I made them differently:
DefaultListModel<String> cityPlace = new DefaultListModel<String>();
JList myList = new JList(cityPlace);
So how can I use the items of the above list in the API??

Related

JList setSelectedValue not working

I have a JList in Swing working bad. I list all items from Database into the list with no problem with this code.
My code:
Integer index = null;
DefaultListModel<String> model = new DefaultListModel<String>();
index = DataBase.getIndex1(cbActivity.getSelectedItem().toString());
activities = DataBase.getIndex2(index);
for(MapActivity mapActitivy : activities)
{
model.addElement(mapActivity.getActivity().toString());
}
jList.setModel(model);
But now, I would like to select individual or multiple selection, but nothing I tried works. I tried:
jList.setSelectedValue("Ball", true);
//jList.setSelectedIndex(2);
jList.setSelectionBackground(Color.red);
But nothing happen. Just the list on screen with nothing selected. Single or multiple.
Any help?
Try this:
setSelectedIndex(1); // here use index of items
or if it does not work use below one:
setSelectedItem("ball") // here use name of item.

Populating JComboBox using an MultiDimensional Array List

I have been trying to populate a Eclipse GUI Java JComboBox using an Array list using constructors without any luck. This is what I have tried thus far.
import item.Item;
import javax.swing.JComboBox;
import java.util.ArrayList;
public class SelectionScreen{
private JFrame frame;
static ArrayList< Item> list;
private String items;
public static void main (String[] args){
initialize();
}
public void initialize(){
list = new ArrayList< Item >();
list.add(new Item("Strawberry,200,.25,.75);
list.add(new Item("Banana,200,.25,1.00);
list.add(new Item("Oranges,200,.25,2.00);
JcomboBox comboBox = newJcomboBox();
ComboBox.setBounds(63,29,86,22)
frame.getContentPane().add(comboBox);
// here is where I tried to fill the combobox
//comboBox.setModel(new DefaultComboBoxModel(Item.getName()))); //Wrong
//comboBox.setModel(Item.getName); //Wrong
//the following only loads the last item in the list which is Oranges
for(Item i: list{
comboBox.setModel(new DefaultComboBoxModel(New String[] {
i.getName()}));
}
// tried making a different list to collect my fruits.
for(Item i: list){
list2[ i.getName()];
Item.length;
} //which was a complete fail.
I am at complete lost here and not very experienced with Java. I can load the items just fine using
comboBox.setModel(new DefaultComboBoxModel(new String[]{ "Strawberry","Banana","Oranges"}));
but I won't know what fruits are in the list when I import them from a text file.
Any help would be appreciated.
/*The following only loads the last item in the list which is Oranges.*/
for(Item i: list)
{
comboBox.setModel(new DefaultComboBoxModel(new String[] {
i.getName()}));
}
Don't keep creating a new ComboBoxModel inside the loop. You can't add more than one item to the model if you keep creating a new model. So you only see the last model created with the single item added to it. If you want to use this approach then you would create the model OUTSIDE of the loop and then just add items the model INSIDE the loop.
Actually you don't event need to create a combo box model. You can just add items directly to the combo box:
Something like:
for(Item i: list
{
comboBox.addItem( i.getName() );
}
Another option is to add the Item object directly to the combo box. Then you can use a custom renderer to control which property of the Item object is display in the combo box. Check out Combo Box With Custom Renderer for more information on this approach.
If you wish to show Item objects in a combobox then you should declare the JComboBox to store Item objects. That way you can easily add items without having to do any mucking around with models at all:
JComboBox<Item> itemsCombo = new JComboBox<>();
list.forEach(itemsCombo::add);
The value displayed in the combobox will be whatever is returned by Item.toString. If that's not what you want (because your toString returns a more complete description of the object - generally considered better practice) then it is fairly easy to write your own Custom Renderer.
The only hackish downside of the JComboBox API is that you've got to cast the selected item:
Item selectedItem = (Item)itemsCombo.getSelectedItem();
This is ugly and I wish the API didn't require it but it's a small price to pay to avoid having to define your own model.
You can, in fact, avoid the cast by:
Item selectedItem = itemsCombo.getItemAt(itemsCombo.getSelectedIndex());
But that's just about as ugly.
As an aside, this is one of several areas in which the standard Java tutorial and samples are quite out of date so there's no blame here at all for not knowing to use generics.

ParseQuery: convert from list of prices in database to strings android

​Hi All,
I am trying to build a scrolling custom listview that displays a list of products ordered by Price ascending. However I just realized I was storing the prices as strings which means $1000.00 comes before $2.01 because it is a character and not a number. I have converted my data to a "Number" on Parse and believe the best type to retrieve it is a double (can anyone comment on that for dollar amounts). The problem is I need to keep it as a number convert it to a string and then pass it to the listview for display on a text field. Initially i had
PPI.setProductprice((String) product.get("Price"));
like this:
// Locate the class table named "Products" in Parse.com
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>(
"Products");
// Locate the column named "Price" in Parse.com and order list
// by ascending
query.orderByAscending("Price");
ob = query.find();
for (ParseObject product : ob) {
// Locate images in PrimaryPhoto column
ParseFile productimage = (ParseFile) product.get("PrimaryPhoto");
ProductPopulation PPI = new ProductPopulation();
PPI.setProductname((String) product.get("Name"));
PPI.setProductbrand((String) product.get("Brand"));
PPI.setProductprice((String) product.get("Price"));
PPI.setProductimage(productimage.getUrl());
productpopulationlist.add(PPI);
I then tried putting it into an array of doubles an iterating through it to convert to strings.
My last attempt which probably doesn't make sense was to change it like this:
PPI.setProductprice((Double) product.getDouble("Price"));
I am fairly knew to Android and any help you can give me would be appreciated.
Thanks in advance.
OK so i do not get the context here but what you can do is save the price as a string and when extracting it you could call Integer.parseInt(String intvalue); on the string to convert the value back to int then you can do all operations you ought to do. you can get a disordered array from the server and arrange it at device level that will save you some time and logic.
I don't know what is the ProductPopulation class you use to populate the list, so I can not say what exactly is the best way in your case, but in general a list can be ordered by means of the Collections.sort() method (see the method documentation).
You could sort the list before you add it to your list view. To sort a list the way you need, you must provide a comparator, than obtains the required values (fields or method results) from the objects that comprise your list, compares the obtained values and returns -1, 0, or 1, depending on the comparison result.
It could look somewhat like this:
for (...) {
ItemClass newObject = new ItemClass(); // new list item
// ...here add the values to the list item...
theList.add(newObject); // add the new item to the list
}
// now sort the list before adding it to the list viewer
Collections.sort(theList, new Comparator<ItemClass>() {
#Override
public int compare(ItemClass o1, ItemClass o2) {
// obtain and compare the values you need
return Double.compare(o1.getDouble(), o1.getDouble());
// you could also do something like
// Double.compare(
// Double.parseDouble(o1.getString()),
// Double.parseDouble(o2.getString()));
// but it would be much slower
}
});
// now add the sorted list to the viewer
listViewer.setList(theList);

Java OOP Array from one class to another

I would like to create an array that holds the information (in this case the ID) and then transfer this data into a drop down list.
The below code is where the data will be inputted and where I created the array list:
Person cons_save = new Person();
cons_save.setPersonfirstname(this.jTextField1.getText());
cons_save.setPersonlastname(this.jTextField2.getText());
cons_save.setPersonID(this.jTextField3.getText());
this.jTextField1.setText("");
this.jTextField2.setText("");
this.jTextField3.setText("");
cons_save.savecons();
ArrayList<String> idList = new ArrayList<String>();
idList.add(cons_save.PersonID);
I need that every time that I input the ID and save, the id will transfer to the array and go to a combo box in another field.
The code I am trying to input in the combo box is the following:
Object[] idList = Person.getidList();
JComboBox box = new JComboBox (idList);
But this keeps issuing multiple errors. I have got this code from other questions similar to mine but it is not working

XML Parsing Problem (DOM & SAX Parsing) to print the corresponding data of Item (main tag)

I am doing Doing Dom Parsing from a news website for my android project. But i am finding a trouble.
I want to print the title element of the item tag (main tag).. in the list. And i did it. but i want when i click on the list item the corresponding data (example link, publishdate, title, description) will print in the next intent.For printing the titles in the list only titles of the items came in the array that i am pouring in the list.The remaining data is not coming in the array. So i am confusing in this problem. Can anybody suggest me appropriate suggestion.
Code for printing titles in the list is following :-
Here "messages" is a list.
and "msg" is the object of Message class which has getter nd setter method.
loadFeed(){
try{
BaseFeedParser parser = new BaseFeedParser();
messages = parser.parse();
List<String> titles = new ArrayList<String>(messages.size());
for (Message msg : messages){
titles.add(msg.getTitle());
}
ArrayAdapter<String> adapter =
new ArrayAdapter<String>(this, R.layout.row,titles);
this.setListAdapter(adapter);
} catch (Throwable t){
Log.e("BBCNews",t.getMessage(),t);
}
I see that you use the BaseFeedParser class, so I guess, you started with this article.
The missing data is in the Message object. Actually you just pass the title strings to your array adapter. So now, if you touch one of the titles, you have to (1) get the selected title and (2) look up the corresponding Message object for that title. Then you use this Message object to feed your new intent.

Categories