I'm designing an app that has 4 spinners a text view and a button and according to what they choose it calculates price of translation service.
I want to know how to assign value to an item in spinner and then use it in calculation.
For example one of the items is English so I want to give value 2 so when that person clicks on English value 2 be used in a formula like below.
Result = Value of item selected in spinner 1 * Value of item selected in spinner 2 *Value of item selected in spinner 3 *Value of item selected in spinner 4
Any hint would be useful
The best way is as below:
1. Make a custom Class
class MyClass {
public int Id;
public String Title;
public long Price;
public MyClass (int id,String title,long price){
Id = id;
Title = title;
Price = price;
}
#Override
public String toString() {
return Title;
}
}
2. Use Array Adapter for the spinner with custom model:
new ArrayAdapter<MyClass>(getApplicationContext(),
android.R.layout.simple_dropdown_item_1line, YOUR_LIST_OF_ITEMS);
3. Whenever you want to get the selected item, just do this:
((MyClass)YOUR_SPINNER.getSelectedItem()).Id
by this way you can have access to any parameter in your model.
Important Note :
Do not forget to override toString method in your custom class. that is the method to show title in the spinner.
By using this approach, you would not need to set any listener listener or hold a reference to selected item.
EDIT : use string instead of any custom class
If you want to use string array that is ok. At the end when you are getting the selected item, just search in the array and find the index and use that.
String selectedItem = YOUR_SPINNER.getSelectedItem().toString();
int index = YOUR_STRING_ARRAY_LIST.indexOf(selectedItem);
Related
I am writing a mock hotel reservation system with two menus, employee and guest. Created rooms are stored in a master array called roomArray and added to a list view in the employee menu, and added to a list view in the guest menu. Rooms can be available or booked, however only available rooms are shown in the guest menu list view, so I might have 5 rooms but only 2 show in the guest menu list view. If the user clicks on the second one, I don't want to try and book the index 1 room in the main roomArray static ArrayList because they don’t match up.
For example, say in the employee list view I have three rooms, two of which are booked. In the guest list view, only the available rooms show up. So the list view on the right would show a selected index of 0, but the same index in the master roomArray is 1 for that same room. How can I make an intermediary of array list of available rooms that reference rooms in the master list?
Nathan
Since you are using JavaFX, you should use ObservableList for your rooms. Additionally, you would need to use FilteredList and FXCollections.observableArrayList(extractor).
This is how you can implement it:
public class Room {
public enum State {AVAILABLE, BOOKED}
private final ObjectProperty<State> state = new SimpleObjectProperty<>(AVAILABLE);
public final ObjectProperty<State> stateProperty() { return state; }
public final State getState() { return state.get(); }
public final void setState(final State value) { state.set(state); }
}
Main class:
private final ObservableList<Room> rooms;
public final ObservableList<Room> getRooms() { return rooms; }
private final ObservableList<Room> guestRooms;
public final ObservableList<Room> getGuestRooms() { return guestRooms; }
// Constructor
public MyClass() {
rooms = FXCollections.observableArrayList(room -> new Observable[] {room.stateProperty()});
guestRooms = rooms.filtered(room -> room.getState() == Room.State.AVAILABLE);
}
The guestRooms list is just a wrapper for rooms list, filtered with a Predicate. The filtered list will change according to the rooms list, but it will only react to changes to the list itself (add, remove, replace of elements). To make sure it responds to changes of the state of existing rooms, you need to use FXCollections.observableArrayList(extractor) overload. This overload allows you to control which property in each Room object would also trigger a ListChangeListener.Change, which would also causes the filtered list to update itself.
I have a Course class which has a method to add Items, which can be a note, an assignment, a URL, or just a generic item. All Items are kept in an ArrayList which the Course that created the list keeps up with. My question is from an item inside this ArrayList, how do I get the printLogger that I have attached to the course object in order to attach it to an item when the Item is created?
this from my Course:
public class Course {
private ArrayList<Item> items;
public PrintLogger p1 = null;
public Course(String code, String name) {
this.code = code;
this.name = name;
items = new ArrayList<>();
}
void add(Item item) {
items.add(item);
if (hasPrintLogger() == true) {
log(PrintLogger.INFORMATIONAL, "Adding " + item.toString());
}
}
And Im trying to have in the code that the assignment constructor runs a way to attach the same printLogger that is already on the course.
You could store a reference to the proper Course object in each of the items in the List.
You could also wrap the ArrayList class in your own class and add a field that points to the Course it belongs to if you need it to be a relationship between the List and the Course instead of between the items in the List and the Course.
You could also search each Course object in your system and check if it contains the List in question. However, this solution would scale badly.
I'm doing a project on web scraping using ArrayLists. When I scrape the info, it comes back as item [0] = pencil, item [1] = $1.50. I would like these items to be together, or if possible it would be even better if the prices and item each had their own id, but each was somehow linked together so that I could reference each one separately. Also, sometimes when scraping I get item [2] = paper, item [3] = $5.00, item [4] = wide bound college ruled, where item [4] represents an optional description that was included with the item that would need to be included in the ArrayList or in a separate ArrayList linked by ids as before. Any ideas are appreciated.
If you only need the name and the price, your best solution is to use a Map, works kind of like an ArrayList<T>, but instead of a single element you have a couple <Key,Value>, like <pencil, 1,50>.
If you need more than two values I would suggest to create your own class, for example:
public class Item {
private String name;
private double price;
private String description;
}
With all the extra methods you need, then declare your ArrayList like this;
ArrayList<Item> items = new ArrayList<>()
It would be better to make a class Item width variables for your name, price and description.
Then you can make an ArrayList to store all of your items.
You should model the object as a class, for example "item", and add each value as a variable of the class. For example:
public class item{
private String name;
private double price;
private String description; //If there's no description it could be null
// Constructor
...
// Getters and setters
...
}
You will need to format the price as a double.
I understand how to do the basics of this. As in if I had the following in a text file: (each number represents a new line, wouldn't actually be in the file)
Item1
Item2
Item3
and so on, using the example from this question/answer, I could populate a JComboBox list fine. It adds the line's string as a combobox option.
My issue is that I'm not using a text file that looks like the one above, instead it looks like this:
Item1 6.00
Item2 8.00
Item3 9.00
the numbers being prices I'd have to convert to a double later on. But from that text file the price would be included in the JComboBox, something I don't want to happen. Is there a way to specify the first String of each line? I won't have more than 2 strings per line in the file.
You should create an class that encapsulates this data including the item name and price, and then populate your JComboBox with objects of this class. e.g.,
public class MyItem {
private String itemName;
private double itemCost;
// any more fields?
public MyItem(String itemName, double itemCost) {
this. ///..... etc
}
// getters and setters
}
To have it appear nice, there's a quick and dirty way: give the class a toString() method that prints out just the item name, e.g.,
#Override
public String toString() {
return itemName;
}
... or a more involved and probably cleaner way: give the JComboBox a renderer that shows only the item name.
Edit
You ask:
Ok, just unsure how I go about passing through the values from the file.
You would parse the file and create objects with the data. Pseudo code:
Create a Scanner that reads the file
while there is a new line to read
read the line from the file with the Scanner
split the line, perhaps using String#split(" ")
Get the name token and put it into the local String variable, name
Get the price String token, parse it to double, and place in the local double variable, price
Create a new MyItem object with the data above
Place the MyItem object into your JComboBox's model.
End of while loop
close the Scanner
I'm working on a Java application in Eclipse that pulls data out of a MySQL database. I'm populating a combo box with data. So far I can get the value of a field to show up but I can't figure out how to store the database row's unique ID value. One suggestion I found was to create a custom class that could store both the display value and the id value. However, this doesn't appear to work with the Eclipse widget combo object. This is what I have
import org.eclipse.swt.widgets.Combo;
class myClass {
public static void createCombo(ResultSet rs) {
Combo c = new Combo();
while(rs.next()) {
int id = rs.getInt("id");
int display = rs.getString("display");
comboitem ci = new comboitem(id,display);
c.add(ci);
}
}
}
class comboitem {
private int _id;
private String _display;
public comboitem(int id, String display) {
this._id = id;
this._display = display;
}
public int getID(){
return _id;
}
public String toString(){
return _display;
}
}
The above errors at c.add(ci). It's expecting a string, not an object. Is there a way to do this?
No idea but, I've always felt it was a bad move anyway.
Create a collection/list of comboitems, populate the widget from comboitem.display.
Index in the combo is index in your collection.
Means you can unit test lots of things without a UI or with simple mock, and it keeps you away from desktop specific implementations in your data models.
The combo widget displays an array of String's, so simply concatenate the two values if you want to display them both. I am not sure what your end goal is from your question. If it is to select the appropriate comboitem based on the combo selection, then store the comboitems in a Map and use the combo values as the keys.
Another approach is to use a jface ComboViewer which allows you to set the input to a complex object, provide a label provider and more complex controls around the Combo widget.
You should also look up some information on java coding conventions and not access your database directly from the UI unless this is a very simple application.
You can find some examples on using most SWT widgets here.