How to iterate through ComboBox in Vaadin? - java

I am working with Vaadin and I have some trouble iterating through choices in a ComboBox. I have my object looking like:
class MyObject{
private String text;
private Integer i;
public MyObject(String text,Integer i){
this.text = text;
this.i = i;
}
public String toString(){
return text;
}
//Getters and setters omitted
}
I add it to the box like this:
MyObject o1 = new MyObject("o1",23);
MyObject o2 = new MyObject("o2",44);
ComboBox box=new ComboBox();
box.addItem(o1);
box.addItem(o2);
This works great when I want to get the chosen data:
MyObject o3 = (MyObject)box.getValue();
But now I need to iterate through the choices in the ComboBox and I don't know how. I seem to need some kind of ID but I don't know how to use that. I tried the following with no success but it doesn't work(and is really ugly):
Collection IDs = box.getItemIds();
Iterator it = IDs.iterator();
while(it.hasNext()){
Object id = it.next();
Item item = IDs.getItem(id);
//What to do now?
}
I'd like to keep my object simple and avoid using beans and complex containers. Vaadins examples are mostly for String and that doesn't help me so much. I'd really appreciate any help.

If you look at the javadoc for ComboBox, you'll see that the addItem method is actually defined on the AbstractSelect class, and it actually takes the itemId as the parameter. (This is in turn delegated to the Select's container, which in this default case is an IndexedContainer)
So, Collection IDs=box.getItemIds(); will return you the collection of MyObject - i.e. what you are actually after.

Related

Can not display contents of Arraylist n JTable

I can't figure this out (have been trying to fix this for the past 2-3 hours).
I would like to display the contents of an arraylist, but they do not appear in the table and also there are NO errors, they simply do not appear. Here is my code:
private class examinations{
private int id;
private int candidate_id;
private String date;
private String exam;
private String examNumber;
public examinations(int id, int student_id, String date, String exam, String examNumber) {
this.id = id;
this.student_id = student_id;
this.date = date;
this.exam= exam;
this.examNumber= examNumber;
}
public ArrayList ListExams(){
ArrayList<exams> list = new ArrayList<exams>();
return list;
}
public void addRollToTable(){
DefaultTableModel model = (DefaultTableModel)tableExams.getModel();
ArrayList<exams> list = ListExams();
Object rowData[] = new Object[5];
for(int i = 0; i < list.size(); i++) {
rowData[0] = list.get(i).id;
rowData[1] = list.get(i).student_id;
rowData[2] = list.get(i).date;
rowData[3] = list.get(i).exam;
rowData[4] = list.get(i).examNumber;
model.addRow(rowData);
}
}
}
I tested this loop and the variables coming out of the other list are there, so a System.out.println(list.get(i).exam); will display the correct thing i typed. However the table will NOT display whatever I add in the rowData. It gives, again, no errors. Let me show you the DefaultTableModel code. This code is in the private void initComponents() of my class...
Object [][] data = {};
String[] columnNames = {"Id", "Student_Id", "Date", "Exam",
"Exam_number"};
tableExams= new javax.swing.JTable();
DefaultTableModel model = new DefaultTableModel(data, columnNames);
tableExams.setModel(model);
tableExams.setCursor(new java.awt.Cursor(java.awt.Cursor.TEXT_CURSOR));
jScrollPane4.setViewportView(tableExams);
I've been reading this: DefaultTableModel Class Overview But I still can't find where I am going wrong... Could anyone give a tip?
First of all learn and use Java naming conventions:
Classs names SHOULD start with an upper case character. Can you show me a class in the JDK that does not?
Method should should NOT start with an upper case character. Again, can you show me a method in the JDK the does?
Learn by example and don't make up your own conventions.
so a System.out.println(list.get(i).exam); will display the correct thing i typed
I don't know how this is possible. Your code is as follows:
a) First, you retrieve the ArrayList from the "listExams() method.
ArrayList<exams> list = ListExams();
b) But in the "listExams()" method all you do is create an empty ArrayList.
ArrayList<exams> list = new ArrayList<exams>();
So you are missing the logic that actually adds data to the ArrayList.
Based on the logic provided, you don't even need the ArrayList. Just take the data from the Examination class and add it to the TableModel:
Object rowData[] = new Object[5];
rowData[0] = id;
rowData[1] = student_id;
rowData[2] = date;
rowData[3] = exam;
rowData[4] = examNumber;
model.addRow(rowData);
For a different solution you could create a custom TableModel to hold your "Examination" objects. Check out Row Table Model for a step-by-step example of how this can be done.
OK, I solved it, even though this was just a work around, I'd accept it.
All I did was use this.setVisible(false) and then entered the information in the other JFrame. Clicking add, i make an object of the first JFrame, passed all the variables, used this.dispose() and then called .setVisible(true) to return to the table, which displayed the information. LOL that was a long testing and re-writing of code to actually realize it was something that small...
I am sorry, I did not know where the actual problem was, and yeah thanks a lot for that simple suggestion there camickr. I tried it in the same JFrame and it worked, then I tried it between 2 JFrames and I realized the JFrame with the table DID NOT update the table. repaint() also didn't work. You quite literally helped me out with that small tip, which is all i needed. THANKS!!!!!!

How can I make arrays with own objects in Java in Android Studio.

I have a long piece of code that looks like this
Kwas a1 = new Kwas("Kwas Azotowy(V)", "HNO3");
// etc..
Kwas a17 = new Kwas("Kwas FluorkoWodorowy", "HF");
How can I write it as an Array? I tried something like
Kwas[] a = new Kwas[17]
But it didn`t work.
My "Kwas" class looks like the following:
public class Kwas {
String name;
String formula;
public Kwas( String nazwa, String wzor)
{
name = nazwa;
formula = wzor;
}
void setName(String c)
{
name = c;
}
void setFormula(String c)
{
formula = c;
}
public String getName()
{
return name;
}
public String getFormula() {return formula;}
}
You can do this:
List<Kwas> list = new ArrayList<Kwas>();
list.add(a2);
Just implement an ArrayList like this:
ArrayList<Kwas> newArray= new ArrayList<>();
And then:
newArray.add(a2);
newArray.add(a3);
newArray.add(a4);
newArray.add(a5);
newArray.add(a6);
newArray.add(a7);
...
...
Then if you want to get an specific item just write something like this:
newArray.get(1).getName(); //for example
I can't comment yet, so I have to provide it as an answer. Everyone is answering here how OP can construct a List, but no one is actually answering how he can create an array, which is probably very confusing for OP who might now think you can't create arrays of self-defined objects. You definitely can. But I don't know what the problem is.
Kwas[] a1 = new Kwas[17];
is definitely the right syntax. Are you sure you include the class? Can you post the exact code and error?
My guess is that you didn't import your class. In Android Studio, try placing your cursor after Kwas and pressing Ctrl+Space. This should show a dropdown list. Select the first line and press enter. Now it should have added an import to your class.
ArrayList<yourObjectName> arrayName = new ArrayList<yourObjectName>();
Then .add(object) on every object
You can simply type:
ArrayList<ObjectType> arrayName = new ArrayList<ObjectType>();
Adding Elements:
arrayName.add(someObject);
Removing Elements:
arrayName.remove(arrayName.get(someInteger));
Getting Elements:
arrayName.get(someInteger);
PS: Don't forget to import:
import java.util.ArrayList;

JComboBox fill with enum variable value

I have a JComboBox that I made this way, using an enum for its values:
JComboBox<StudyGrade> maxLevelOfStudiesCombo = new JComboBox<StudyGrade>(StudyGrade.values());
The enum looks like this:
public enum StudyGrade {
ELEMENTARY ("Primaria"),
MIDDLE ("Secundaria"),
MIDDLE_HIGH ("Preparatoria"),
HIGH ("Universidad"),
MASTERS ("Maestría / Posgrado"),
DOCTORATE ("Doctorado"),
POST_DOCTORATE ("Post Doctorado");
private String studies;
private StudyGrade(String studies) {
this.studies = studies;
}
public String getStudies() {
return studies;
}
public void setStudies(String studies) {
this.studies = studies;
}
#Override
public String toString() {
return studies;
}
}
As you can see I'm overriding the toString() method, so I can have the studies values shown instead of the enum ones...
However I want to show the studies values only in the JComboBox not everytime I use the StudyGrade enum.
How would I change the code, so whenever I use something like:
System.out.println(StudyGrade.HIGH);
I get printed HIGH instead of Universidad, but not for the JComboBox?
I'm overriding the toString() method, so I can have the studies values shown instead of the enum ones...
I've never used a enum before but I assume you can use it like any custom object added to the combo box so you should be able to use a custom renderer so you can control which data is displayed by the combo box.
Check out Combo Box With Custom Renderer for more information and a helper class.
You're looking to extend an enum, but that's impossible. It means that something is wrong with your requirement.
Rendering is done in the UI component, and it's not enum's business to deal with presentation of data. You should make you UI component render enum the way you'd like instead of trying to make enum understand where it's being used. Since you're a Swing fanatic you should know how to do that, something like this:
maxLevelOfStudiesCombo.setRenderer(new DefaultListCellRenderer() {
#Override
public Component getListCellRendererComponent(JList<?> jList, Object o, int i, boolean b, boolean b1) {
Component rendererComponent = super.getListCellRendererComponent(jList, o, i, b, b1);
setText(o instanceof StudyGrade ? ((StudyGrade) o).getStudies() : o.toString());
return rendererComponent;
}
});
That's going to do that.
You could just remove the toString override as the default toString for an enum is to return the name of the enum element.
And you could just have a simple for loop that would iterate through the values in your enums and add it to a string array. Then, you would need to pass that array as the argument for your JComboBox and it should be gold.
The code for it should look a bit like that:
//get all study grades
StudyGrade[] temp = StudyGrade.values();
//create a string array of same length as the array
String[] str = new String[temp.length];
//append all the studies value to the string array
for(int i = 0; i< temp.length; i++){
str[i] = temp[i].getStudies();
System.out.println(temp[i]);//debug
}
System.out.println("---------------------");//debug
for(String s : str){//debug
System.out.println(s);//debug
}//debug
//pass it
JComboBox<StudyGrade> maxLevelOfStudiesCombo = new JComboBox<StudyGrade>(StudyGrade.values());
Here is an example I made on repl.it
https://repl.it/GH28/1

Getting an object variable from List in C#

I have class with variables:
public class Items {
public string name;
public string ID;
}
and I have second class when I have List of object of first class
public class MyClass {
public Items cheese;
public List <Items> listOfItems = new List ();
listOfItems.Add (cheese); // I know it should be in method or something but it's just an example
}
and I want get the name of the cheese, but using my list, because I have above 20 items in my list.
In Java I can do it like:
listOfItems.get(1).name; // 1 is an index
How can I do it in C#?
// Please don't try to improve my
listOfItems[0].name;
Just remember to start counting at 0 ;)
Other than that its works the same way as java, just slightly different syntax
The simple way:
listOfItems[1].name;
If you want a specific item try this:
var name = listOfItems.Find(x => x.ID == "1").name;
"1" is the example "Id" that you search.
Sorry for my english
I hope help you.

Access to array from other class

static LifeInsurance[] LIArray = new LifeInsurance[20];
public LifeInsurance ( float dMonth, int startD,int startM,int startY,int label){
LifeInsurance.LIArray[LifeInsurance.counterLI] = this;
this.dMonth = dMonth;
this.startD = startD;
this.startM = startM;
this.startY = startY;
this.label = Individual.l;
this.codeLΙ = counterLI;
counterLI++;
}
I've got this array in LifeInsurance class, and I want to have access to this.label = Individual.l;
from an other class.
How can this be possible? Thanks in advance!
Create a geter and setter for the static variable. Get that instance of the class to get the static variable(array in this case) and fetch the object from the array that you need . Then use the getter for label.
To access it via class, you should do:
lInsurance = new LifeInsurance(args......);
lInsurance.label; //if label is visible from the class you're calling, otherwise:lI
lInsurance.getLabel(); //you'll need to define this method.
Create getter:
public String getLabel(){
return this.label;
}
And call:
lInsurance = new LifeInsurance(args......);
lInsurance.getLabel();
There is a subtle security problem with your code. You add this to the package-access LIArray variable before this is fully constructed. Another thread can therefore look at the half-constructed this, which can (rarely) cause all sorts of problems.
By the way, what is CounterLI? You probably should use a List or Map for the list of all life insurance policies instead of an array.
leo21 is right. It seems that you want a later access to one of your Insurances, so this would be :
A getter for the Insurances array :
public static LifeInsurance[] getInsurances() {
return LIArray;
}
Plus a getter for the required attribute :
public String getLabel() {
return this.label;
}
Then you can access it statically from anywhere by :
String a_label = LifeInsurance.getInsurances()[an_index].getLabel();
Note : The getter for the array must be static.
It is quite a long time I haven't coded in Java, so the syntax might be incorrect (edit me if necessary), but this is the idea...

Categories