JavaFX tableview not displaying properly [closed] - java

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I have a JavaFX application with a scene with two tableviews, the first one works correctly, the second one doesn't.
The second tableview only displays the content of 2 out of the 5 columns it should, and the content on the second column, should be actually on the last column. I have used javaFX a few times before and it's the first time I see something like this, I revised my code 2 or 3 times looking for things that could be wrong or mispelled, but I haven't been able to find it.
This is what the tableview displays.
This is the code of the object class it contains.
public class Producte {
private int codi;
private String nom;
private String descripcio;
private float preu;
private int codiFabricant;
public Producte(String nom, String descripcio, float preu,
int codiFabricant) {
this.nom = nom;
this.descripcio = descripcio;
this.preu = preu;
this.codiFabricant = codiFabricant;
}
public Producte(int codi, String nom, String descripcio, float preu,
int codiFabricant) {
this.codi = codi;
this.nom = nom;
this.descripcio = descripcio;
this.preu = preu;
this.codiFabricant = codiFabricant;
}
public int getCodi() {
return codi;
}
public void setCodi(int codi) {
this.codi = codi;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getDescripcio() {
return descripcio;
}
public void setDescripcio(String descripcio) {
this.descripcio = descripcio;
}
public float getPreu() {
return preu;
}
public void setPreu(float preu) {
this.preu = preu;
}
public int getCodiFabricant() {
return codiFabricant;
}
public void setCodiFabricant(int codiFabricant) {
this.codiFabricant = codiFabricant;
}
#Override
public String toString() {
return "Producte [codi=" + codi + ", nom=" + nom + ", descripcio="
+ descripcio + ", preu=" + preu + ", codiFabricant="
+ codiFabricant + "]";
}
}
And this is the code from the method that loads the scene.
The first tableview is the dirTable, the second one(the one that doesn't work properly is the prodTable). Thanks in advance for any help :/
static Scene directorScene() {
GridPane gridPane = new GridPane();
gridPane.setAlignment(Pos.CENTER);
gridPane.setVgap(25);
gridPane.setHgap(25);
director = DirectorFunctions.director;
final ObservableList<Director> dirList = FXCollections.observableArrayList();
dirList.add(director);
TableView<Director> dirTable = new TableView<>();
dirTable.setItems(dirList);
TableColumn<Director, String> fabCol = new TableColumn<>("Fabricant");
TableColumn<Director, String> dniCol = new TableColumn<>("DNI");
TableColumn<Director, String> nomCol = new TableColumn<>("Nom");
TableColumn<Director, String> mailCol = new TableColumn<>("Mail");
TableColumn<Director, String> passCol = new TableColumn<>("Pass");
fabCol.setCellValueFactory(new PropertyValueFactory<Director,String>("Nom"));
dniCol.setCellValueFactory(new PropertyValueFactory<Director,String>("DniDirector"));
nomCol.setCellValueFactory(new PropertyValueFactory<Director,String>("NomDirector"));
mailCol.setCellValueFactory(new PropertyValueFactory<Director,String>("MailDirector"));
passCol.setCellValueFactory(new PropertyValueFactory<Director,String>("PasswordDirector"));
dirTable.getColumns().setAll(fabCol, dniCol, nomCol, mailCol, passCol);
dirTable.setMinWidth(450);
dirTable.setMaxHeight(52);
dirTable.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
gridPane.add(dirTable, 0, 0);
Button modificarDirector = new Button("Modificar");
modificarDirector.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
// TODO Auto-generated method stub
}
});
gridPane.add(modificarDirector, 1, 0);
final ObservableList<Producte> prodList = FXCollections.observableArrayList();
for (Producte p:DirectorFunctions.productes.values()) {
prodList.add(p);
}
TableView<Producte> prodTable = new TableView<>();
prodTable.setItems(prodList);
TableColumn<Producte, String> codiPCol = new TableColumn<>("Codi");
TableColumn<Producte, String> nomPCol = new TableColumn<>("Nom");
TableColumn<Producte, String> descPCol = new TableColumn<>("Descripció");
TableColumn<Producte, String> preuPCol = new TableColumn<>("Preu");
TableColumn<Producte, String> fabPCol = new TableColumn<>("Fabricant");
codiPCol.setCellValueFactory(new PropertyValueFactory<Producte, String>("Codi"));
nomPCol.setCellValueFactory(new PropertyValueFactory<Producte, String>("Nom"));
nomPCol.setCellValueFactory(new PropertyValueFactory<Producte, String>("Descripcio"));
nomPCol.setCellValueFactory(new PropertyValueFactory<Producte, String>("Preu"));
nomPCol.setCellValueFactory(new PropertyValueFactory<Producte, String>("CodiFabricant"));
prodTable.getColumns().setAll(codiPCol, nomPCol, descPCol, preuPCol, fabPCol);
prodTable.setMinWidth(450);
prodTable.setMaxHeight(200);
prodTable.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
gridPane.add(prodTable, 0, 1);
Button nouButton = new Button("Nou");
nouButton.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
// TODO Auto-generated method stub
}
});
nouButton.setMinWidth(75);
Button modButton = new Button("Modificar");
modButton.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
// TODO Auto-generated method stub
}
});
modButton.setMinWidth(75);
Button delButton = new Button("Borrar");
delButton.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
// TODO Auto-generated method stub
}
});
delButton.setMinWidth(75);
Button backButton = new Button("Tornar");
backButton.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
// TODO Auto-generated method stub
}
});
backButton.setMinWidth(75);
gridPane.add(backButton, 1, 2);
VBox vbox = new VBox(25);
vbox.getChildren().addAll(nouButton, modButton, delButton);
gridPane.add(vbox, 1, 1);
Scene scene = new Scene(gridPane, 640, 480, Color.web("eee"));
return scene;
}
This is the Director class for whoever wants to see it as well
public class Director {
private int codi;
private String nom;
private String dniDirector;
private String nomDirector;
private String mailDirector;
private String passwordDirector;
public Director(int codi, String nom, String dniDirector,
String nomDirector, String mailDirector, String passwordDirector) {
this.codi = codi;
this.nom = nom;
this.dniDirector = dniDirector;
this.nomDirector = nomDirector;
this.mailDirector = mailDirector;
this.passwordDirector = passwordDirector;
}
public int getCodi() {
return codi;
}
public void setCodi(int codi) {
this.codi = codi;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getDniDirector() {
return dniDirector;
}
public void setDniDirector(String dniDirector) {
this.dniDirector = dniDirector;
}
public String getNomDirector() {
return nomDirector;
}
public void setNomDirector(String nomDirector) {
this.nomDirector = nomDirector;
}
public String getMailDirector() {
return mailDirector;
}
public void setMailDirector(String mailDirector) {
this.mailDirector = mailDirector;
}
public String getPasswordDirector() {
return passwordDirector;
}
public void setPasswordDirector(String passwordDirector) {
this.passwordDirector = passwordDirector;
}
#Override
public String toString() {
return "Fabricant [codi=" + codi + ", nom=" + nom + ", dniDirector="
+ dniDirector + ", nomDirector=" + nomDirector
+ ", mailDirector=" + mailDirector + ", passwordDirector="
+ passwordDirector + "]";
}
}

I would advice you to use JavaFX Property for all your model. You can find samples in here.
PropertyValueFactory<S,T> looks for a property of type T in S with the same name that you typed in the constructor.
For example, in a model class Product which has a StringProperty field name,
new PropertyValueFactory<Product, String>("name")
will look for :
nameProperty()
and if it doesn't find it, it will further look for getName() and wrap it in a ReadOnlyObjectWrapper before returning it.
From the docs,
If no method matching this pattern exists, there is fall-through
support for attempting to call get() or is() (that
is, getFirstName() or isFirstName() in the example above). If a method
matching this pattern exists, the value returned from this method is
wrapped in a ReadOnlyObjectWrapper and returned to the TableCell
The problem in your example is that your table column has a cellValueFactory which says,
nomPCol.setCellValueFactory(new PropertyValueFactory<Producte, String>("Preu"));
but your getter method is returning a float instead of a String
public float getPreu() {
return preu;
}

I found the problem already, I used copy+paste to duplicate lines of the code and I forgot to change the name on the columns for the table. I'm an idiot -__-.
Sorry for wasting your time guys...
By the way, is there a way to close a thread/question without having to ask mods or something?

Related

Simple problem with method getting default valuse from class [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 24 days ago.
Improve this question
I started to learn java and i cant get past my problem with method getting default vaules from class. The code is about cars and garage. Everything works just as I intended with the execption of returning default values for Samochod s1 instead of the values that were set in the main function.
Main:
public static void main(String[] args) {
Samochod s1 = new Samochod("Fiat", "126p", 2, 650, 6.0);
Samochod s2 = new Samochod("Syrena", "105", 2, 800, 7.6);
Garaz g1 = new Garaz();
g1.setAdres( "ul. Garażowa 1" );
g1.setPojemnosc( 1 );
Garaz g2 = new Garaz("ul. Garażowa 2", 2);
g1.wprowadzSamochod(s1);
g1.wypiszInfo();
g1.wprowadzSamochod(s2);
g2.wprowadzSamochod(s2);
g2.wprowadzSamochod(s1);
g2.wypiszInfo();
g2.wyprowadzSamochod();
g2.wypiszInfo();
g2.wyprowadzSamochod();
g2.wyprowadzSamochod();
}
package Lab2_02;
public class Samochod {
private String marka;
private String model;
private int iloscDrzwi;
private int pojemnoscSilnika;
private double srednieSpalanie;
private static int iloscSamochodow = 0;
public String getMarka() {
return marka;
}
public String getModel() {
return model;
}
public int getIloscDrzwi() {
return iloscDrzwi;
}
public int getPojemnoscSilnika() {
return pojemnoscSilnika;
}
public double getSrednieSpalanie() {
return srednieSpalanie;
}
public void setMarka(String marka) {
this.marka = marka;
}
public void setModel(String model) {
this.model = model;
}
public void setIloscDrzwi(int iloscDrzwi) {
this.iloscDrzwi = iloscDrzwi;
}
public void setPojemnoscSilnika(int pojemnoscSilnika) {
this.pojemnoscSilnika = pojemnoscSilnika;
}
public void setSrednieSpalanie(double stednieSpalanie) {
this.srednieSpalanie = stednieSpalanie;
}
public Samochod() {
marka = "nieznany";
model = "nieznany";
iloscDrzwi = 0;
pojemnoscSilnika = 0;
srednieSpalanie = 0.0;
iloscSamochodow++;
}
public Samochod(String marka_, String model_, int iloscDrzwi_, int pojemnoscSilnika_, double srednieSpalanie_) {
marka = marka_;
model = model_;
iloscDrzwi = iloscDrzwi_;
pojemnoscSilnika = pojemnoscSilnika_;
srednieSpalanie = srednieSpalanie_;
iloscSamochodow++;
}
public double obliczSpalanie(double dlugoscTrasy) {
double spalanie = (srednieSpalanie * dlugoscTrasy)/100;
return spalanie;
}
public double obliczKosztPrzejazdu(double dlugoscTrasy, double cenaPaliwa) {
double kosztPrzejazdu = obliczSpalanie(dlugoscTrasy) * cenaPaliwa;
return kosztPrzejazdu;
}
public void wypiszInfo() {
System.out.println("Marka: " + marka);
System.out.println("Model: " + model);
System.out.println("Ilosc drzwi: " + iloscDrzwi);
System.out.println("Pojemnosc silnika: " + pojemnoscSilnika);
System.out.println("Srednie spalanie: " + srednieSpalanie);
}
public static void wypiszIloscSamochodow() {
System.out.println("Ilosc samochodow: " + iloscSamochodow);
}
}
package Lab2_02;
public class Garaz {
private String adres;
private int pojemnosc;
private int liczbaSamochodow = 0;
private Samochod [] samochody;
public String getAdres() {
return adres;
}
public int getPojemnosc() {
return pojemnosc;
}
public void setAdres(String adres) {
this.adres = adres;
}
public void setPojemnosc(int pojemnosc) {
this.pojemnosc = pojemnosc;
samochody = new Samochod[pojemnosc];
}
public Garaz() {
adres = "nieznany";
pojemnosc = 0;
samochody = null;
}
public Garaz(String adres_, int pojemnosc_) {
adres = adres_;
pojemnosc = pojemnosc_;
samochody = new Samochod[pojemnosc];
}
public void wprowadzSamochod(Samochod s) {
if(liczbaSamochodow >= pojemnosc) {
System.out.println("W garazu jest maksymalna ilość pojazdow.");
}
else {
samochody [liczbaSamochodow] = new Samochod();
liczbaSamochodow++;
System.out.println("Samochod zostal wprowadzony.");
}
}
public void wyprowadzSamochod() {
if(liczbaSamochodow == 0) {
System.out.println("W garazu nie ma zadnego auta.");
}
else {
samochody [liczbaSamochodow-1] = null;
liczbaSamochodow--;
System.out.println("Samochod zostal wyprowadzony.");
}
}
public void wypiszInfo(){
for(int i = 0; i <= liczbaSamochodow-1; i++){
samochody[i].wypiszInfo();
}
}
}
So my problem is that instead of returning in console info about my car "Fiat", it say "nieznany" from default class. I know it is simple problem but i can't get past it for a few days. My problem is with this line:
public void wypiszInfo(){
for(int i = 0; i <= liczbaSamochodow-1; i++){
samochody[i].wypiszInfo();
Instead of showing this:
Samochod zostal wprowadzony.
Marka: nieznany
Model: nieznany
Ilosc drzwi: 0
Pojemnosc silnika: 0
Srednie spalanie: 0.0
I can't make it show this:
Marka: Fiat
Model: 126p
Ilosc drzwi: 2
Pojemnosc silnika: 650
Srednie spalanie: 6.0
In wprowadzSamochod(Samochod s) method you're creating a new Samochod instance, instead of using the one passed as parameter. Since you have a default constructor, you are always using it, setting information to default values:
public void wprowadzSamochod(Samochod s) {
if(liczbaSamochodow >= pojemnosc) {
System.out.println("W garazu jest maksymalna ilość pojazdow.");
}
else {
samochody [liczbaSamochodow] = new Samochod(); // <-- there
liczbaSamochodow++;
System.out.println("Samochod zostal wprowadzony.");
}
}
How it should be:
public void wprowadzSamochod(Samochod s) {
if(liczbaSamochodow >= pojemnosc) {
System.out.println("W garazu jest maksymalna ilość pojazdow.");
}
else {
samochody [liczbaSamochodow] = s; // <-- there
liczbaSamochodow++;
System.out.println("Samochod zostal wprowadzony.");
}
}
Just a micro-suggestion: inside the exit condition of a for loop you can just use i < max, instead of i <= max-1 (e.g. in wypiszInfo()).

How to highlight words in TextView based on data

I want to highlight the text in the TextView that matches the data taken from the database. I use the code below but the text in the TextView doesn't change color.
Here's my code, but the setters and getters looks useless.
class getICT {
#SerializedName("eng")
private String eng;
#SerializedName("bhs")
private String bhs;
#SerializedName("kor")
private String kor;
public getICT(String eng, String bhs, String kor, String imageURL){
this.eng = eng;
this.bhs = bhs;
this.kor = kor;
}
/*
GETTERS N SETTERS
*/
public String getEng() {
return eng;
}
public String getBhs() {
return bhs;
}
public String getKor() {
return kor;
}
#Override
public String toString() {
return eng;
}
}
This is my interface, get from database
interface MyAPIService {
#GET("/ICT03/danger.php")
Call<getICT[]> getICT();
}
I write the code for highlight the text from here
ShowDetected.MyAPIService myAPIService = ShowDetected.RetrofitClientInstance.getRetrofitInstance().create(ShowDetected.MyAPIService.class);
Call<getICT[]> call = myAPIService.getICT();
call.enqueue(new Callback<getICT[]>() {
#Override
public void onResponse(Call<getICT[]> call, Response<getICT[]> response) {
getICT[] icts = response.body();
String s = showInput.getText().toString();
for(int i = 0; i < icts.length; i++) {
if (icts[i].equals(s)) {
showInput.setText(s);
showInput.setTextColor(Color.RED);
} else {
showInput.setTextColor(Color.BLACK);
}
}
}
#Override
public void onFailure(Call<getICT[]> call, Throwable t) {
Toast.makeText(ShowDetected.this, ""+t.getMessage().toString(), Toast.LENGTH_SHORT).show();
}
});
Your code is incorrect, try this
boolean isHighlight = false
for(int i = 0; i < icts.length; i++) {
if (icts[i].equals(s)) {
isHighlight = true;
break;
}
}
showInput.setTextColor(isHighlight ? Color.RED : Color.BLACK);

(identifier expected) getter/setter and objects

I've got a problem with my programm. When i try to compile following i just receive the message:
Tutorium.java:15: error: <identifier> expected
public void settName(vorlesung.lectureName) {
^
So my Code:
Tutorium.java
public class Tutorium {
private Vorlesung vorlesung;
public String tName;
private int tNumber;
public int gettNumber() {
return this.tNumber;
}
public String gettName() {
return this.tName;
}
public void settName(vorlesung.lectureName) {
this.tName = vorlesung.lectureName;
}
public String toString() {
return (this.tName + ", " + this.tNumber);
}
public Tutorium(int tNumber){
this.tNumber = tNumber; } }
Vorlesung.java
public class Vorlesung {
public String lectureName;
private int lectureNumber;
private int lecture;
private Dozent dozent;
private String lecturerlName;
public String getlectureName(){
return this.lectureName;
}
public int lectureNumber(){
return this.lectureNumber;
}
public int lecture(){
return this.lecture;
}
public String getlecturer(){
this.lecturerlName = dozent.lecturerlName;
return this.lecturerlName;
}
public String toString() {
return (this.lectureName + ", " + this.lectureNumber);
}
public Vorlesung(String lectureName, int lecture) {
this.lectureName = lectureName;
this.lecture = lecture +1;
this.lectureNumber = this.lecture -1;
this.lecturerlName = lecturerlName;
}}
My Main-Method:
public class MainVorlesung {
public static void main(String[] args) {
Student student = new Student("STUDENTNAME", "STUDENTLASTNAME", 178, 1);
Vorlesung vorlesung = new Vorlesung("Programmieren", 13341);
Tutorium tutorium = new Tutorium(3);
Dozent dozent = new Dozent("LECTURERFIRSTNAME", "LECTURERLASTNAME", 815);
System.out.println(student.toString());
System.out.println(vorlesung.toString());
System.out.println(tutorium.toString());
System.out.println(dozent.toString());
}}
My goal is to set the value of tName equal the value of vorlesung.lectureName.
Why can't i do this that way?
I appreciate every help. :)
Thanks
For methods, the arguments that you pass in must have a declared value.
In this case, a String. So you need to change your method to this:
public void settName(String newLectureName) {
this.tName = newLectureName;
}
Read more about what a java method is and how to create one here: http://www.tutorialspoint.com/java/java_methods.htm
Change settName to
public void settName(String name) {
this.tName = name;
}
Since your goal is:
My goal is to set the value of tName equal the value of vorlesung.lectureName.
You should get rid of the setName method entirely since it will depend entirely on the vorlesung field and so should not be changeable. You should also get rid of the tName field, and instead change getName() to:
public class Tutorium {
private Vorlesung vorlesung;
// public String tName; // get rid of
private int tNumber;
public String gettName() {
if (vorlesung != null) {
return vorlesung.getlecturer();
}
return null; // or throw exception
}
// *** get rid of this since you won't be setting names
// public void settName(Vorlesung vorlesung) {
// this.tName = vorlesung.lectureName;
// }
I have just now noticed that your Tutorium class does not have and absolutely needs a setVorlesung(...) method.
public void setVorlesung(Vorlesung vorlesung) {
this.vorlesung = vorlesung;
}

Update highlighted cell in javafx

I use two text fields and a button to add entries to a two column table.
If I add a new entry the table is updated right away:
private void addBtn(ActionEvent event) {
Test o = new Test();
o.setTitle(title.getText());
o.setCount(Integer.parseInt(count.getText()));
mainApp.getData().add(o);
}
In a second step I added an additional button to amend the highlighted count cell:
private void editBtn(ActionEvent event) {
Test o = getSelection();
o.setCount(Integer.parseInt(count.getText()));
mainApp.getData().set(tablePosition, o);
}
If I click the button, the cell will update the value, but it's not visible in the table. If I click the button a second time it will update the table.
To check for which row is highlighted I use the following functions:
private final ListChangeListener<Test> selector = new ListChangeListener<Test>() {
#Override
public void onChanged(ListChangeListener.Change<? extends Test> c) {
setSelection();
}
};
public Test getSelection() {
if (testTable != null) {
List<Test> table = testTable.getSelectionModel().getSelectedItems();
if (table.size() == 1) {
final Test selection = table.get(0);
return selection;
}
}
return null;
}
private void setSelection() {
final Test o = getSelection();
tablePosition = mainApp.getData().indexOf(o);
if (o != null) {
title.setText(o.getTitle());
count.setText(o.getCount().toString());
}
}
In the initialize method I add a listener to the observable list:
final ObservableList<Test> t1 = testTable.getSelectionModel().getSelectedItems();
t1.addListener(selector);
My Test class:
public class Test {
private final SimpleStringProperty title = new SimpleStringProperty();
private final SimpleIntegerProperty count = new SimpleIntegerProperty();
public void setTitle(String title) {
this.title.set(title);
}
public String getTitle() {
return title.get();
}
public void setCount(Integer count) {
this.count.set(count);
}
public Integer getCount() {
return count.get();
}
}
How can I make the Edit button to update the cell value right away?
Assuming you are using a PropertyValueFactory as the cell factory for your table columns, you need to provide property accessor methods in order that the table cell provided by the PropertyValueFactory can listen to those properties for changes.
One correct implementation of using the JavaFX Property model looks like
public class Test {
private final IntegerProperty count = new SimpleIntegerProperty(this, "count", 0);
private final StringProperty title = new SimpleStringProperty(this, "title", "");
public final int getCount() {
return count.get();
}
public final void setCount(int count) {
this.count.set(count);
}
public IntegerProperty countProperty() {
return count ;
}
public final String getTitle() {
return title.get();
}
public final void setTitle(String title) {
this.title.set(title);
}
public StringProperty titleProperty() {
return title ;
}
}
With that, the following method will then correctly update the selected row in the table:
private void editBtn(ActionEvent event) {
Test o = testTable.getSelectionModel().getSelectedItem();
if (o != null) {
o.setCount(Integer.parseInt(count.getText()));
}
}
If that doesn't fix the problem for you, I recommend you edit your question completely and provide a sscce that demonstrates the problem.

Hashmap overwriting values

Hey im trying to make a hashMap store for planes. But when i add, it will only print out one flight. Can anyone help me with this.
Here is my code:
import java.util.Scanner;
public class MainApp
{
private Scanner keyboard = new Scanner(System.in);
public static void main(String[] args)
{
new MainApp().start();
}
public void start()
{
Airline aerLingus = new Airline("AerLingus");
PlaneStore planeStore = new PlaneStore("Aer Lingus");
Flight p1 = new Flight("Aer Lingus","A01", 150.5, 10.5, 500, Flight.AIRPLANETYPE.AIRBUS);
Flight p2 = new Flight("Aer Lingus","B01", 50.3, 1.5, 91, Flight.AIRPLANETYPE.CORPORATE);
Flight p3 = new Flight("Aer Lingus","C01", 12.2, -3.1, 56, Flight.AIRPLANETYPE.AIRBUS);
Flight p4 = new Flight("Ryan Air","D01", 10.5, 1.5, 430, Flight.AIRPLANETYPE.PRIVATE);
Flight p5 = new Flight("Ryan Air","E01", 0.3, 2.1, 101, Flight.AIRPLANETYPE.CORPORATE);
Flight p6 = new Flight("Ryan Air","F01", 2.2, -3, 291, Flight.AIRPLANETYPE.AIRBUS);
planeStore.addFlight("",p1);
planeStore.addFlight("",p2);
planeStore.addFlight("",p3);
planeStore.print();
aerLingus.add(planeStore);
aerLingus.add(planeStore);
aerLingus.add(planeStore);
aerLingus.printPlane();
}
}
import java.util.TreeMap;
public class PlaneStore
{
private String airlineName;
private TreeMap<String,Flight> planeMap;
public PlaneStore(String airlineName)
{
this.airlineName = "";
planeMap = new TreeMap<String,Flight>();
}
public String getAirlineName() {
return airlineName;
}
public TreeMap<String, Flight> getFlightList() {
return planeMap;
}
public void addFlight(String airline,Flight flight)
{
planeMap.put(airline, flight);
}
// ---------------------------------------------------------------------------------------
// Name: Print.
// ---------------------------------------------------------------------------------------
public void print()
{
System.out.println("\n********Student's in the Company.********");
for (Flight flight : planeMap.values()) {
// System.out.println(employee); to print the toString of Employee
// class
// or:
System.out.println("Airline:\t" + flight.getAirline());
System.out.println("Flight Number:\t" + flight.getFlightNumber());
System.out.println("Fuel Remaining:\t" + flight.getFuelRemaining());
}
}
}
public class Flight
{
private String airline;
private String flightNumber;
private double fuelRemaining;
private double overdue;
private int passengerNumber;
private AIRPLANETYPE planeType;
public enum AIRPLANETYPE
{
AIRBUS("1"), CORPORATE("2"), PRIVATE("3");
private String planeName;
private AIRPLANETYPE(String planeName)
{
this.planeName = planeName;
}
}
public Flight(String airline, String flightNumber, double fuelRemaining,
double overdue, int passengerNumber, AIRPLANETYPE planeType)
{
super();
this.airline = airline;
this.flightNumber = flightNumber;
this.fuelRemaining = fuelRemaining;
this.overdue = overdue;
this.passengerNumber = passengerNumber;
this.planeType = planeType;
}
public String getAirline() {
return airline;
}
public void setAirline(String airline) {
this.airline = airline;
}
public String getFlightNumber() {
return flightNumber;
}
public void setFlightNumber(String flightNumber) {
this.flightNumber = flightNumber;
}
public double getFuelRemaining() {
return fuelRemaining;
}
public void setFuelRemaining(double fuelRemaining) {
this.fuelRemaining = fuelRemaining;
}
public double getOverdue() {
return overdue;
}
public void setOverdue(double overdue) {
this.overdue = overdue;
}
public int getPassengerNumber() {
return passengerNumber;
}
public void setPassengerNumber(int passengerNumber) {
this.passengerNumber = passengerNumber;
}
public AIRPLANETYPE getPlaneType() {
return planeType;
}
public void setPlaneType(AIRPLANETYPE planeType) {
this.planeType = planeType;
}
public String toString()
{
return "Flight [airline=" + airline + ", flightNumber=" + flightNumber
+ ", fuelRemaining=" + fuelRemaining + ", overdue=" + overdue
+ ", passengerNumber=" + passengerNumber + ", planeType="
+ planeType + "]";
}
}
HashMap is a data structure in which you are able to store key-value pairs. It essential that the key is unique. Otherwise you overwrite the value that has the same key.
With this data structure you are able to add and find values very quickly because the complexity of adding and finding values is constant. But the disadvantage is that you can only add a key one time.
EDIT in response to further code posting:
Every time you do PlaneStore.addPlane() you are providing a blank key. A Hashmap is only useful if you provide a unique key for every object. Otherwise every plane will overwrite the previous plane. This is why when you print you only see a single object. Give every plane a unique key, possibly a tail number or something related, and you should be able to retrieve every object.
You need to define your hashmap as follows:
Map<String, List<Flight>> map = new TreeMap<String, List<Flight>>();
and then for each flight name you need to create a new list of flights as follows:
map.get("foo") = new ArrayList<Flight>();
map.get("foo").add(Flight);
for above code, you need to be defensive, if there is no list, you need to create one, otherwise you ll get some exception. moreover, ensure that only one list will be created per flight key.

Categories

Resources