DynamicJasper - How to add a subreport as columns? - java

Overview
I have a Java class which has an ArrayList that must be printed to
the jasperReport as a subreport.
I'm using DynamicJasper library.
The example on this question has been modified so it can be reproduced. However the data is different on the real case.
Problem
The current code Ive come with, prints the subreport in another line. Its ugly. I wanted the subreport to just be a group of columns that are concatenated.
To make it clear, here's the current result
And What I want is something like this:
Current code
public class Test_subReport {
protected static JasperPrint jp;
protected static JasperReport jr;
protected static Map params = new HashMap();
protected static DynamicReport dr;
public static void main(String args[]) throws SQLException, ColumnBuilderException, ClassNotFoundException {
Test_subReport t = new Test_subReport();
t.createReport();
}
public void createReport() throws SQLException, ColumnBuilderException, ClassNotFoundException {
ArrayList<Fruit> createMockDataset = createMockDataset();
Style titleStyle = new Style();
titleStyle.setHorizontalAlign(HorizontalAlign.CENTER);
titleStyle.setFont(Font.ARIAL_SMALL_BOLD);
Style dataStyle = new Style();
dataStyle.setHorizontalAlign(HorizontalAlign.CENTER);
dataStyle.setFont(Font.ARIAL_SMALL);
dataStyle.setBlankWhenNull(true);
final List items = SortUtils.sortCollection(createMockDataset, Arrays.asList(new String[]{"name", "description"}));
FastReportBuilder drb = new FastReportBuilder();
drb.setTemplateFile("templatePortrait.jrxml", true, true, true, true);
drb.addColumn("name", "name", String.class.getName(), 30, dataStyle)
.addColumn("description", "description", String.class.getName(), 50, dataStyle)
.setTitle("Report")
.setSubtitle("")
.setPrintBackgroundOnOddRows(true)
.setUseFullPageWidth(true);
drb.addGroups(2);
try {
drb.addField("evaluations", List.class.getName());
drb.addSubreportInGroupHeader(1, createSubreport("Evaluations"));
} catch (Exception ex) {
Logger.getLogger(Test_subReport.class.getName()).log(Level.SEVERE, null, ex);
}
DynamicReport dynamicReport = drb.build();
dynamicReport.setTitleStyle(titleStyle);
HashMap parametros = new HashMap();
parametros.put("dataRelatorio", MyTools.getDataPorExtenso());
doReport(dynamicReport, items, parametros);
}
public void doReport(final DynamicReport _report, final Collection _data, HashMap parametros) {
try {
JRDataSource beanCollectionDataSource = new JRBeanCollectionDataSource(_data);
JasperPrint jasperPrint = DynamicJasperHelper.generateJasperPrint(_report, new ClassicLayoutManager(), beanCollectionDataSource, parametros);
JasperViewer.viewReport(jasperPrint);
} catch (JRException ex) {
ex.printStackTrace();
}
}
private DynamicReport createHeaderSubreport(String title) throws Exception {
FastReportBuilder rb = new FastReportBuilder();
DynamicReport dr = rb
.addColumn("id", "id", Integer.class.getName(), 100)
.addColumn("score", "score", Double.class.getName(), 50)
.setMargins(5, 5, 20, 20)
.setUseFullPageWidth(true)
.setWhenNoDataNoPages()
.setTitle(title)
.build();
return dr;
}
private Subreport createSubreport(String title) throws Exception {
SubReportBuilder srb = new SubReportBuilder();
srb.setDynamicReport(createHeaderSubreport(title), new ClassicLayoutManager())
.setStartInNewPage(true)
.setDataSource(DJConstants.DATA_SOURCE_ORIGIN_FIELD, DJConstants.DATA_SOURCE_TYPE_COLLECTION, "evaluations");
return srb.build();
}
public ArrayList<Fruit> createMockDataset() {
ArrayList<Fruit> fruits = new ArrayList<>();
Fruit f1 = new Fruit();
f1.name = "Apple X1";
f1.description = "Yummy yummy apple for the stackoverflow readers 1";
Fruit f2 = new Fruit();
f2.name = "Apple Ag";
f2.description = "Yummy yummy apple for the stackoverflow readers 2";
Fruit f3 = new Fruit();
f3.name = "Apple Mn";
f3.description = "Yummy yummy apple for the stackoverflow readers 3";
Fruit f4 = new Fruit();
f4.name = "Apple O2";
f4.description = "Yummy yummy apple for the stackoverflow readers 4";
//Evaluations for f1
for (int i = 0; i < 4; i++) {
Evaluation e = new Evaluation();
e.id = i;
e.score = Math.random() * 10;
f1.evaluations.add(e);
}
//evaluations for f4
for (int i = 0; i < 4; i++) {
Evaluation e = new Evaluation();
e.id = i;
e.score = Math.random() * 10;
f4.evaluations.add(e);
}
fruits.add(f1);
fruits.add(f2);
fruits.add(f3);
fruits.add(f4);
return fruits;
}
public class Fruit {
public String name;
public String description;
public ArrayList<Evaluation> evaluations = new ArrayList<Evaluation>();
public Fruit() {
}
public Fruit(String name, String description) {
this.name = name;
this.description = description;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public ArrayList<Evaluation> getEvaluations() {
return evaluations;
}
public void setEvaluations(ArrayList<Evaluation> evaluations) {
this.evaluations = evaluations;
}
}
public class Evaluation {
public int id;
public double score;
public Evaluation() {
}
public Evaluation(int id, double score) {
this.id = id;
this.score = score;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
}
}

Probably there isn't way to implement desired behavior using subreports.
I guess, that the best way to do it is to use just groups, but data model should be a bit modified for that.
Here is my solution:
public class Test_subReport {
protected static JasperPrint jp;
protected static JasperReport jr;
protected static Map params = new HashMap();
protected static DynamicReport dr;
public static void main(String args[]) throws SQLException, ColumnBuilderException, ClassNotFoundException {
Test_subReport t = new Test_subReport();
t.createReport();
}
public void createReport() throws SQLException, ColumnBuilderException, ClassNotFoundException {
List<DataWrapper> createMockDataset = wrapData(createMockDataset());
Style titleStyle = new Style();
titleStyle.setHorizontalAlign(HorizontalAlign.CENTER);
titleStyle.setFont(Font.ARIAL_SMALL_BOLD);
Style dataStyle = new Style();
dataStyle.setHorizontalAlign(HorizontalAlign.CENTER);
dataStyle.setFont(Font.ARIAL_SMALL);
dataStyle.setBlankWhenNull(true);
final List items = SortUtils.sortCollection(createMockDataset, Arrays.asList(new String[]{"name", "description"}));
FastReportBuilder drb = new FastReportBuilder();
drb.setTemplateFile("templatePortrait.jrxml", true, true, true, true);
drb.addColumn("name", "name", String.class.getName(), 30, dataStyle)
.addColumn("description", "description", String.class.getName(), 100, dataStyle)
.addColumn("id", "id", Integer.class.getName(), 30, dataStyle)
.addColumn("score", "score", Double.class.getName(), 30, false, "$ #.00", dataStyle)
.setTitle("Report")
.setWhenNoDataNoPages()
.setAllowDetailSplit(false)
.setUseFullPageWidth(true);
drb.addGroups(2);
DynamicReport dynamicReport = drb.build();
dynamicReport.setTitleStyle(titleStyle);
HashMap parametros = new HashMap();
parametros.put("dataRelatorio", MyTools.getDataPorExtenso());
doReport(dynamicReport, items, parametros);
}
public void doReport(final DynamicReport _report, final Collection _data, HashMap parametros) {
try {
JRDataSource beanCollectionDataSource = new JRBeanCollectionDataSource(_data);
JasperPrint jasperPrint = DynamicJasperHelper.generateJasperPrint(_report, new ClassicLayoutManager(), beanCollectionDataSource, parametros);
JasperViewer.viewReport(jasperPrint);
} catch (JRException ex) {
ex.printStackTrace();
}
}
public List<DataWrapper> wrapData(List<Fruit> fruits) {
List<DataWrapper> dataList = new ArrayList<>();
for (Fruit fruit : fruits) {
if (fruit.getEvaluations().isEmpty()) {
dataList.add(new DataWrapper(fruit.name, fruit.description, null, null));
} else {
for (Evaluation evaluation : fruit.getEvaluations()) {
dataList.add(new DataWrapper(fruit.name, fruit.description, evaluation.id, evaluation.score));
}
}
}
return dataList;
}
public List<Fruit> createMockDataset() {
ArrayList<Fruit> fruits = new ArrayList<>();
Fruit f1 = new Fruit();
f1.name = "Apple X1";
f1.description = "Yummy yummy apple for the stackoverflow readers 1";
Fruit f2 = new Fruit();
f2.name = "Apple Ag";
f2.description = "Yummy yummy apple for the stackoverflow readers 2";
Fruit f3 = new Fruit();
f3.name = "Apple Mn";
f3.description = "Yummy yummy apple for the stackoverflow readers 3";
Fruit f4 = new Fruit();
f4.name = "Apple O2";
f4.description = "Yummy yummy apple for the stackoverflow readers 4";
//Evaluations for f1
for (int i = 0; i < 4; i++) {
Evaluation e = new Evaluation();
e.id = i;
e.score = Math.random() * 10;
f1.evaluations.add(e);
}
//evaluations for f4
for (int i = 0; i < 4; i++) {
Evaluation e = new Evaluation();
e.id = i;
e.score = Math.random() * 10;
f4.evaluations.add(e);
}
fruits.add(f1);
fruits.add(f2);
fruits.add(f3);
fruits.add(f4);
return fruits;
}
public class Fruit {
public String name;
public String description;
public ArrayList<Evaluation> evaluations = new ArrayList<Evaluation>();
public Fruit() {
}
public Fruit(String name, String description) {
this.name = name;
this.description = description;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public ArrayList<Evaluation> getEvaluations() {
return evaluations;
}
public void setEvaluations(ArrayList<Evaluation> evaluations) {
this.evaluations = evaluations;
}
}
public class Evaluation {
public int id;
public double score;
public Evaluation() {
}
public Evaluation(int id, double score) {
this.id = id;
this.score = score;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
}
public class DataWrapper {
public String name;
public String description;
public Integer id;
public Double score;
public DataWrapper() {
}
public DataWrapper(String name, String description, Integer id, Double score) {
this.name = name;
this.description = description;
this.id = id;
this.score = score;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Double getScore() {
return score;
}
public void setScore(Double score) {
this.score = score;
}
}
}
And here is the result:
Feel free to ask if you have some question.

Related

Return more that one ArrayList

I'm trying to deal with this baking JSON:
in android app so this is the class to bring the JSON data from link:
OpenBakingJsonUtils.java:
public final class OpenBakingJsonUtils {
public static ArrayList<ArraysLists> getSimpleBakingStringsFromJson(Context context, String bakingJsonString)
throws JSONException {
final String ID = "id";
final String NAME = "name";
final String SERVINGS = "servings";
final String INGREDIENTS = "ingredients";
final String STEPS = "steps";
final String QUANTITY = "quantity";
final String MEASURE = "measure";
final String INGREDIENT = "ingredient";
final String IDSTEPS = "id";
final String SHORTDESCRIPTION = "shortDescription";
final String DESCRIPTION = "description";
final String VIDEOURL = "videoURL";
final String THUMBNAILURL = "thumbnailURL";
ArrayList<ArraysLists> parsedRecipeData = new ArrayList<ArraysLists>();
ArrayList<BakingItem> Baking = new ArrayList<BakingItem>();
JSONArray recipeArray = new JSONArray(bakingJsonString);
for (int i = 0; i < recipeArray.length(); i++) {
int id;
String name;
int servings;
double quantity;
String measure;
String ingredient;
int idSteps;
String shortDescription;
String description;
String videoURL;
String thumbnailURL;
JSONObject recipeObject = recipeArray.getJSONObject(i);
id = recipeObject.getInt(ID);
name = recipeObject.getString(NAME);
servings = recipeObject.getInt(SERVINGS);
ArrayList<IngredientsItem> Ingredients = new ArrayList<IngredientsItem>();
JSONArray ingredientsArray = recipeObject.getJSONArray(INGREDIENTS);
for(int j = 0 ; j< ingredientsArray.length(); j++) {
JSONObject ingredientsObject = ingredientsArray.getJSONObject(j);
quantity = ingredientsObject.getDouble(QUANTITY);
measure = ingredientsObject.getString(MEASURE);
ingredient = ingredientsObject.getString(INGREDIENT);
Ingredients.add(new IngredientsItem(quantity, measure, ingredient));
}
ArrayList<StepsItem> Steps = new ArrayList<StepsItem>();
JSONArray stepsArray = recipeObject.getJSONArray(STEPS);
for(int j = 0 ; j< stepsArray.length(); j++) {
JSONObject stepsObject = stepsArray.getJSONObject(j);
idSteps = recipeObject.getInt(IDSTEPS);
shortDescription = stepsObject.getString(SHORTDESCRIPTION);
description = stepsObject.getString(DESCRIPTION);
videoURL = stepsObject.getString(VIDEOURL);
thumbnailURL = stepsObject.getString(THUMBNAILURL);
Steps.add(new StepsItem(idSteps, shortDescription, description, videoURL, thumbnailURL));
}
Baking.add(new BakingItem(id, name, servings, Ingredients, Steps));
parsedRecipeData.add(new ArraysLists(Baking, Ingredients, Steps));
}
return parsedRecipeData;
}
}
as you see there are 3 ArrayList classes:
ArrayList<BakingItem>
ArrayList<IngredientsItem>
ArrayList<StepsItem>
and this is the code for each one:
BakingItem.java:
public class BakingItem implements Parcelable {
private int id;
private String name;
private int servings;
private ArrayList<IngredientsItem> ingredients = new ArrayList<IngredientsItem>();
private ArrayList<StepsItem> steps = new ArrayList<StepsItem>();
public BakingItem(int id, String name, int servings, ArrayList<IngredientsItem> ingredients, ArrayList<StepsItem> steps) {
this.id = id;
this.name = name;
this.servings = servings;
this.ingredients = ingredients;
this.steps = steps;
}
#Override
public void writeToParcel(Parcel out, int flags) {
out.writeInt(id);
out.writeString(name);
out.writeInt(servings);
out.writeTypedList(ingredients);
out.writeTypedList(steps);
}
private BakingItem(Parcel in) {
this.id = in.readInt();
this.name = in.readString();
this.servings = in.readInt();
ingredients = new ArrayList<IngredientsItem>();
in.readTypedList(ingredients, IngredientsItem.CREATOR);
}
public BakingItem() {
}
#Override
public int describeContents() {
return 0;
}
public static final Parcelable.Creator<BakingItem> CREATOR = new Parcelable.Creator<BakingItem>() {
#Override
public BakingItem createFromParcel(Parcel in) {
return new BakingItem(in);
}
#Override
public BakingItem[] newArray(int i) {
return new BakingItem[i];
}
};
public int getId() {
return id;
}
public String getName() {
return name;
}
public int getServings() {
return servings;
}
}
IngredientsItem.java:
public class IngredientsItem implements Parcelable {
private double quantity;
private String measure;
private String ingredient;
public IngredientsItem(double quantity, String measure, String ingredient) {
this.quantity = quantity;
this.measure = measure;
this.ingredient = ingredient;
}
#Override
public void writeToParcel(Parcel out, int flags) {
out.writeDouble(quantity);
out.writeString(measure);
out.writeString(ingredient);
}
private IngredientsItem(Parcel in) {
this.quantity = in.readDouble();
this.measure = in.readString();
this.ingredient = in.readString();
}
public IngredientsItem() {
}
#Override
public int describeContents() {
return 0;
}
public static final Parcelable.Creator<IngredientsItem> CREATOR = new Parcelable.Creator<IngredientsItem>() {
#Override
public IngredientsItem createFromParcel(Parcel in) {
return new IngredientsItem(in);
}
#Override
public IngredientsItem[] newArray(int i) {
return new IngredientsItem[i];
}
};
public double getQuantity() {
return quantity;
}
public String getMeasure() {
return measure;
}
public String getIngredient() {
return ingredient;
}
}
as well as the StepsItem class
and the forth is the ArraysLists.java which contain all the 3 arrays above and returned by the OpenBakingJsonUtils.java:
Then I'm trying to call these JSON data in different activities
so in MainActivity.java in loadInBackground:
Override
public ArrayList<BakingItem> loadInBackground() {
URL recipeRequestUrl = NetworkUtils.buildUrl();
try {
String jsonBakingResponse = NetworkUtils.getResponseFromHttpUrl(recipeRequestUrl);
ArrayList<ArraysLists> simpleJsonBakingData = OpenBakingJsonUtils.getSimpleBakingStringsFromJson(MainActivity.this, jsonBakingResponse);
return simpleJsonBakingData;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
I call the returned ArrayList from OpenBakingJsonUtils.java which is in this case the ArraysLists,
then in DetailActivity.java in doInBackground:
#Override
protected ArrayList<ArraysLists> doInBackground(Object... params) {
if (params.length == 0) {
return null;
}
URL reviewsRequestUrl = NetworkUtils.buildUrl();
try {
String jsonReviewResponse = NetworkUtils.getResponseFromHttpUrl(reviewsRequestUrl);
ArrayList<ArraysLists> simpleJsonReviewData = OpenBakingJsonUtils.getSimpleBakingStringsFromJson(DetailsActivity.this, jsonReviewResponse);
return simpleJsonReviewData;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
here I call the ArrayList of ArraysLists too but the problem in adapters of MainActivity.java and DetailsActivity.java in onBindViewHolder:
holder.CommentContent.setText(String.valueOf(mCommentsItems.get(position).getQuantity()));
it just says that cannot resolve method getQuantity() which is in IngredientsItem.java while I used the ArraysLists.java that returned by OpenBakingJsonUtils.java
so what should I do to call methods from BakingItem.java and IngredientsItem.java while I use the returned ArraysLists.java ?

Adding information into an array with super classes

The problem I'm having is with the superclass. I can't change the new Property(...) to another class called House. The only difference is the information in them, but once I change it I am getting an error stating that the constructor doesn't match but I thought that the super() should pass the information on.
This is how my Array is set up:
public static void main(String[] args) {
Property [] Properties = new Property[25];
Properties[0] = new Property (1001, 200, "58 Lackagh Park", "Dungiven", "BT47 4ND", new MyDate(15,05,2018), 5000.00, 800.50, 40.50);
Properties[1] = new Property (1002, 500, "24 Jop Lane", "Kelflar", "VT57 5LP", new MyDate(10,06,2018), 12000.00, 1000.00, 60.00);
Properties[2] = new Property (1003, 100, "Lot B", "Bandlebop", "LU49 3JU", new MyDate(01,07,2018), 450.00, 800.00, 50.50);
Properties[3] = new Property (1004, 200, "12 Back Lane", "Galafray", "GA1 1Fy", new MyDate(05,12,2018), 50000.00, 1000.00, 80.00);
Properties[4] = new Property (1005, 200, "43 Pop Street", "Jundar", "BY78 1JH", new MyDate(11,12,2018), 2500.00, 600.50, 32.90);
Properties[5] = new Property (1006, 200, "123 Fake Street", "Dunlem", "BL09 4PL", new MyDate(21,03,2018), 65000.00, 700.50, 56.50);
Properties[6] = new Property (1007, 200, "09012 Bakers Field", "Bristol", "LO87 D0N", new MyDate(15,05,2018), 5000.00, 200.50, 40.50);
Properties[7] = new Property (1008, 200, "Unit B high Street", "LA", "LA58 7NL", new MyDate(18,11,2018), 20000.00, 1000.00, 90.00);
Properties[8] = new Property (1009, 200, "1 Flabbergast Park", "Nubb", "HJ98 7NH", new MyDate(10,03,2018), 4958.00, 900.20, 20.50);
Properties[9] = new Property (1010, 200, "29 Bakers Field", "London Town", "HU84 2JO", new MyDate(02,05,2018), 1234.00, 800.00, 40.50);
Properties[10] = new Property (1011, 200, "20 Peliper Lane", "Dungiven", "BT47 4FE", new MyDate(15,05,2018), 4321.00, 900.00, 20.00);
Here is the Property class:
public class Property {
private int PropertyNumber, SquareFoot;
private String Address,Town,PostCode;
private MyDate DateListed;
public double Price;
private double Rates;
private double PricePerSquareFoot;
public Property() {
PropertyNumber = 0;
SquareFoot = 0;
Address = "";
Town = "";
PostCode = "";
DateListed = new MyDate();
Price = 0.0;
Rates = 0.0;
PricePerSquareFoot = 0.0;
}
public Property(int PropertyNumber, int SquareFoot, String Address, String Town, String PostCode, MyDate DateListed, double Price, double rates, double PricePerSquareFoot)
{
super();
this.PropertyNumber = PropertyNumber;
this.SquareFoot = SquareFoot;
this.Address = Address;
this.Town = Town;
this.PostCode = PostCode;
this.DateListed = DateListed;
this.Price = Price;
this.Rates = Rates;
this.PricePerSquareFoot = PricePerSquareFoot;
}
//--------Getters and setters----------------//
public void setPropertyNumber(int PropertyNumber)
{
this.PropertyNumber = PropertyNumber;
}
public int getPropertyNumber()
{
return PropertyNumber;
}
public void setSquareFoot(int SquareFoot)
{
this.SquareFoot = SquareFoot;
}
public int getSquareFoot()
{
return SquareFoot;
}
public void setAddress(String Address)
{
this.Address = Address;
}
public String getAddress()
{
return Address;
}
public void setTown( String Town)
{
this.Town = Town;
}
public String getTown()
{
return Town;
}
public void setPostcode( String PostCode)
{
this.PostCode = PostCode;
}
public String GetPostcode()
{
return PostCode;
}
public void setDateListed(MyDate DateListed)
{
this.DateListed = DateListed;
}
public MyDate getDateListed()
{
return DateListed;
}
public void setPrice(double Price)
{
this.Price = Price;
}
public double getPrice()
{
return Price;
}
public void setRates(double Rates)
{
this.Rates = Rates;
}
public double getRates()
{
return Rates;
}
public void setPricePerSquareFoot(double PricePerSqaureFoot)
{
this.PricePerSquareFoot = PricePerSquareFoot;
}
public double getPricePerSquareFoot()
{
return PricePerSquareFoot;
}
And this is what I am trying to put into the array along with the property information such as Property number price etc:
public class House extends Residential {
private int Garden;
private int Garage;
public House() {
super();
Garage = 0;
Garden = 0;
}
public House(int Garage, int garden) {
super();
this.Garage = 0;
this.Garden = 0;
}
public void setGarage(int Garage)
{
this.Garage = Garage;
}
public int getGarage()
{
return Garage;
}
public void setGarden(int Garden)
{
this.Garden = Garden;
}
public int getGarden()
{
return Garden;
}
.......
This is the residential class
public class Residential extends Property
{
private int NumberOfBedrooms;
private int NumberOfBathrooms;
public Residential()
{
super();
NumberOfBedrooms = 0;
NumberOfBathrooms = 0;
}
public void setNumberOfBedrooms(int NumberOfBedrooms)
{
this.NumberOfBedrooms = NumberOfBedrooms;
}
public int getNumberOfBedrooms()
{
return NumberOfBedrooms;
}
public void setNumberOfBathrooms(int NumberOfBathrooms)
{
this.NumberOfBathrooms = NumberOfBathrooms;
}
public int getNumberOfBathrooms()
{
return NumberOfBathrooms;
}
public Residential(int NumberOfBedrooms, int NumberOfBathrooms)
{
super();
NumberOfBedrooms = 0;
NumberOfBathrooms = 0;
}

Created add() method to insert objects into an array and all i get are null values

this is a class called Doglist to add the object to an array.
public class DogList {
private int numItems;
private DogItem[] dogListArray;
private int position;
DogList () {
numItems=0;
position = 0;
dogListArray = new DogItem[10];
}
public void add (DogItem item) {
dogListArray[numItems++]= new DogItem(item.getName(),
item.getBreed(),
item.getWeight(),
item.getOwner1(),
item.getOwner2()
);
}
public String toString() {
String result = "";
for (int i=0; i<numItems; i++) {
result += dogListArray[i].toString() + "\n";
}
return result;
}
public DogItem searchForDogItem (DogItem gi) {
System.out.println("Here is your obj value: " + gi );
return null;
}//This is the one im having trouble with.
}
I have all the setters and getters in the DogItem class.
and this is from the UI where i get the dog info(name, breed, weight, owners1&2 names)
public void searchForItem (String name ) {
DogItem gi = new DogItem (name);
gi = gl.searchForDogItem(gi);
if (gi==null) {
msgTextField.setText("Dog Not Found");
} else {
nameTextField.setText(String.valueOf(gi.getName()));
breedTextField.setText(String.valueOf(gi.getBreed()));
weightTextField.setText(String.valueOf(gi.getWeight()));
owner1TextField.setText(String.valueOf(gi.getOwner1()));
owner2TextField.setText(String.valueOf(gi.getOwner2()));
}
}
Ill try and clear things up as i go.
this is the output i get
Here is your obj value: null null 0.0 null null
Ok so here is what it probably should look like instead. Just from what I saw wrong already. However you'd probably want to override the toString() method of DogItem.
Main method example of this:
public class Main {
public static void main(String[] args) {
DogItem dogItem = new DogItem("Spot", "Dalmation", "45", "Bob", "Sandy");
DogItem.add(dogItem);
DogItem result = DogItem.searchForItem("Spot");
if (result == null) {
System.out.println("Dog not found");
// GUI error output goes here
} else {
System.out.println("Here is your obj value: " + result);
// Where your GUI stuff goes
}
}
}
DogItem example of this:
public class DogItem {
private static DogItem[] dogListArray = new DogItem[100];
private static int numItems = 0;
private String name;
private String breed;
private String weight;
private String owner1;
private String owner2;
public DogItem(String name, String breed, String weight, String owner1, String owner2) {
this.name = name;
this.breed = breed;
this.weight = weight;
this.owner1 = owner1;
this.owner2 = owner2;
}
public static void add(DogItem dogItem) {
dogListArray[numItems++] = dogItem;
}
public static DogItem searchForItem(String name) {
DogItem dogItem = null;
for (DogItem result : dogListArray) {
if (result != null) {
if (result.getName() == name) {
dogItem = result;
}
}
}
return dogItem;
}
#Override
public String toString() {
String result = name + ", " + breed + ", " + weight + ", " + owner1 + " " + owner2;
return result;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getBreed() {
return breed;
}
public void setBreed(String breed) {
this.breed = breed;
}
public String getWeight() {
return weight;
}
public void setWeight(String weight) {
this.weight = weight;
}
public String getOwner1() {
return owner1;
}
public void setOwner1(String owner1) {
this.owner1 = owner1;
}
public String getOwner2() {
return owner2;
}
public void setOwner2(String owner2) {
this.owner2 = owner2;
}
}
These would be recommended changes from me though:
private static ArrayList<String> owners;
private static ArrayList<DogItem> dogsList;
public DogItem(String name, String breed, String weight, String owner) {
this.name = name;
this.breed = breed;
this.weight = weight;
this.owners.add(owner);
}
public void init() {
owners = new ArrayList<String>();
dogsList = new ArrayList<DogItem>();
}
public void addDog(DogItem dogItem) {
dogsList.add(dogItem);
}
public DogItem searchForItem(String name) {
DogItem dogItem = null;
for (DogItem result : dogsList) {
if (result != null) {
if (result.getName() == name) {
dogItem = result;
}
}
}
return dogItem;
}
public void addOwner(String owner) {
owners.add(owner);
}
public String getOwner() {
return owners.get(owners.size() - 1);
}

Can't get ComboboxTableCell in javafx app

I am trying to show a combobox for each record that is fetched from database,but unfortunatley i can't get any combobox in expected column.
Here is code for my model class:
public class Employee {
private final int id;
private final SimpleStringProperty ename;
private final SimpleStringProperty ecnic;
private final SimpleDoubleProperty ebalance;
private final SimpleDoubleProperty etotalpaid;
private SimpleStringProperty estatus;
public Employee(int id, String ename, String ecnic, Double ebalance,
Double etotalpaid, String estatus) {
super();
this.id = id;
this.ename = new SimpleStringProperty(ename);
this.ecnic = new SimpleStringProperty(ecnic);
this.ebalance = new SimpleDoubleProperty(ebalance);
this.etotalpaid = new SimpleDoubleProperty(etotalpaid);
this.estatus = new SimpleStringProperty(estatus);
}
public String getEstatusproperty() {
return estatus.get();
}
public String getEstatus() {
return estatus.get();
}
public void setEstatus(String estatus) {
this.estatus = new SimpleStringProperty(estatus);
}
public int getId() {
return id;
}
public String getEname() {
return ename.get();
}
public String getEcnic() {
return ecnic.get();
}
public Double getEbalance() {
return ebalance.get();
}
public Double getEtotalpaid() {
return etotalpaid.get();
}
}
Here is code for my method that i call to fetch data from database..
public void attendence() throws SQLException{
employeelist = FXCollections.observableArrayList();
ename.setCellValueFactory(new PropertyValueFactory<Employee,String>("ename"));
ecnic.setCellValueFactory(new PropertyValueFactory<Employee,String>("ecnic"));
ebalance.setCellValueFactory(new PropertyValueFactory<Employee,Double>("ebalance"));
etotalpaid.setCellValueFactory(new PropertyValueFactory<Employee,Double>("etotalpaid"));
estatus.setCellValueFactory(new PropertyValueFactory<Employee,String>("estatus"));
estatus.setCellFactory(ComboBoxTableCell.forTableColumn(new DefaultStringConverter(), attendenceoptions));
estatus.setOnEditCommit(
new EventHandler<CellEditEvent<Employee, String>>() {
#Override
public void handle(CellEditEvent<Employee, String> t) {
((Employee) t.getTableView().getItems().get(t.getTablePosition().getRow())).setEstatus(t.getNewValue());
};
});
estatus.setEditable(true);
stmt = conn.createStatement();
sql = "select * from employe";
rs = stmt.executeQuery(sql);
while(rs.next()){
employeelist.add(new Employee(rs.getInt(1),rs.getString(2),rs.getString(3),rs.getDouble(5),rs.getDouble(6),"Present"));
employeetable.setItems(employeelist);
}
stmt.close();
rs.close();
}
}
Added this in method to solve issue.
employeetable.setEditable(true);

ArrayList of Objects from a different class

New to Java.
I have a txt file:
hat, 20, 1
pants, 50, 45
shoes, 100, 10
In one class called Goods I have been able to read it, split it using delimiter, add it to an ArrayList.
I have another class called GoodsList where I will be creating an ArrayList which should have the above as an object that I can use if the user requests it. Thanks
I think you are asking about java generics.
If so, create your Goods class since you need to access it as an object via the ArrayList.
public Class Goods implements Serializable {
private String goodName;
private double price;
private int quantity;
public String getGoodName() {
return goodName;
}
public void setGoodName(String goodName) {
this.goodName = goodName;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
}
and then Write your GoodsList class to create the list with Goods object you set:
public class GoodsList {
public static void main(String args[]) {
Goods g = new Goods();
Goods g2 = new Goods();
Goods g3 = new Goods();
g.setGoodName("hat");
g.setQuantity(50);
g.setPrice(100.00);
g2.setGoodName("pants");
g2.setQuantity(50);
g2.setPrice(100.00);
g3.setGoodName("shoes");
g3.setQuantity(50);
g3.setPrice(100.00);
List < Goods > goodsList = new ArrayList < Goods > ();
goodsList.add(g);
goodsList.add(g2);
goodsList.add(g3);
//printing goods:
for (Goods g: goodsList) {
System.out.println(g.getGoodName() + "," + g.getQuantity() + "," + g.getPrice());
}
}
}
is that what you're looking for?
Are you looking for something like:
public class FileReaderExample
{
public class Goods
{
private String goodName = null;
private String price = null;
private String quantity = null;
public Goods(String goodName ,String price,String quantity)
{
this.goodName = goodName;
this.price = price;
this.quantity = quantity;
}
public String getGoodName()
{
return goodName;
}
public void setGoodName(String goodName)
{
this.goodName = goodName;
}
public String getPrice()
{
return price;
}
public void setPrice(String price)
{
this.price = price;
}
public String getQuantity()
{
return quantity;
}
public void setQuantity(String quantity)
{
this.quantity = quantity;
}
}
private ArrayList<Goods> populateGoods()
{
ArrayList<Goods> goodsList = new ArrayList<Goods>();
File file = new File("d:\\text.txt");
try
{
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null)
{
String[] itemsOnLine = line.trim().split(",");
goodsList.add(new Goods(itemsOnLine[0],itemsOnLine[1],itemsOnLine[2]));
}
}
catch (IOException e)
{
e.printStackTrace();
}
return goodsList;
}
public static void main(String[] args)
{
FileReaderExample fileReaderExample = new FileReaderExample();
ArrayList<Goods> goodsList = fileReaderExample.populateGoods();
for (Goods goods : goodsList)
{
System.out.println(goods.getGoodName());
}
}
}

Categories