Anybody help me? I want to change row color in TableView depending on value.
For example: i want to change row color to green color when value in column colType is equal to "good"
This is my method where Im filling TableView with data from database:
public void setCustomers() {
List<Customer> list = customer.getTable(); //getting results from database
data = FXCollections.observableArrayList();
Integer count = 1;
for (Customer customer1 : list) {
data.add(new CustomerObj(count++, customer1.getId(), customer1.getName(),
form.formatDate(customer1.getBorn().toString()), customer1.getStreet(),
customer1.getCity(), customer1.getIdCustomerType().getPhrase()));
}
tblCustomer.setItems(data);
tblCustomer.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
colID.setCellValueFactory(cell -> cell.getValue().getPropertyId());
colName.setCellValueFactory(cell -> cell.getValue().getPropertyName());
colBorn.setCellValueFactory(cell -> cell.getValue().getPropertyBorn());
colAddr.setCellValueFactory(cell -> cell.getValue().getPropertyAddr());
colCity.setCellValueFactory(cell -> cell.getValue().getPropertyCity());
colType.setCellValueFactory(cell -> cell.getValue().getPropertyType());
rowOptions.setCellValueFactory(new PropertyValueFactory<>("Button"));
editCust(); //just filling TableCell with Button
rowOptions1.setCellValueFactory(new PropertyValueFactory<>("Button"));
deleteCust(); //just filling TableCell with Button
}
And this is the CustomerObj class:
package sk.evka.fp.obj;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
public class CustomerObj {
private SimpleIntegerProperty id;
private SimpleIntegerProperty idDB;
private SimpleStringProperty name;
private SimpleStringProperty born;
private SimpleStringProperty addr;
private SimpleStringProperty city;
private SimpleStringProperty type;
public CustomerObj(Integer i, Integer id, String n, String b, String a, String c, String t) {
this.id = new SimpleIntegerProperty(i);
this.idDB = new SimpleIntegerProperty(id);
this.name = new SimpleStringProperty(n);
this.born = new SimpleStringProperty(b);
this.addr = new SimpleStringProperty(a);
this.city = new SimpleStringProperty(c);
this.type = new SimpleStringProperty(t);
}
public Integer getId() {
return id.get();
}
public Integer getIdDB() {
return idDB.get();
}
public String getName() {
return name.get();
}
public String getBorn() {
return born.get();
}
public String getAddr() {
return addr.get();
}
public String getCity() {
return city.get();
}
public String getType() {
return type.get();
}
public void setId(Integer i) {
this.id = new SimpleIntegerProperty(i);
}
public void setIdDB(Integer i) {
this.idDB = new SimpleIntegerProperty(i);
}
public void setName(String n) {
name = new SimpleStringProperty(n);
}
public void setBorn(String b) {
born = new SimpleStringProperty(b);
}
public void setAddr(String a) {
addr = new SimpleStringProperty(a);
}
public void setCity(String c) {
city = new SimpleStringProperty(c);
}
public void setType(String t) {
type = new SimpleStringProperty(t);
}
public SimpleIntegerProperty getPropertyId() {
return id;
}
public SimpleIntegerProperty getPropertyIdDB() {
return idDB;
}
public SimpleStringProperty getPropertyName() {
return name;
}
public SimpleStringProperty getPropertyBorn() {
return born;
}
public SimpleStringProperty getPropertyAddr() {
return addr;
}
public SimpleStringProperty getPropertyCity() {
return city;
}
public SimpleStringProperty getPropertyType() {
return type;
}
public void setPropertyId(SimpleIntegerProperty i) {
this.id = i;
}
public void setPropertyIdDB(SimpleIntegerProperty i) {
this.idDB = i;
}
public void setPropertyName(SimpleStringProperty n) {
name = n;
}
public void setPropertyBorn(SimpleStringProperty b) {
born = b;
}
public void setPropertyAddr(SimpleStringProperty a) {
addr = a;
}
public void setPropertyCity(SimpleStringProperty c) {
city = c;
}
public void setPropertyType(SimpleStringProperty t) {
type = t;
}
}
i havent found an answer to this nowhere.
If you want to color the whole row, use a rowFactory that changes the color of the TableRows it creates according to item property.
Furthermore you better use JavaFX properties appropriately:
Properties are not meant to be replaced themselfs. The property getter should always return the same property instance or at least instances that store listeners in a common data structure; Otherwise the value could be modified without the possibility of being notified of that fact (replacing the property with a property containing a new value).
public static class Item {
// property only assigned once
private final StringProperty type;
public Item(String type) {
this.type = new SimpleStringProperty(type);
}
// getter for value wrapped in property
public final String getType() {
return this.type.get();
}
// setter for value wrapped in property
public final void setType(String value) {
this.type.set(value);
}
// property getter
public final StringProperty typeProperty() {
return this.type;
}
}
public static Color typeToColor(String type) {
if (type == null) {
return Color.WHITESMOKE;
}
switch (type) {
case "bad":
return Color.RED;
case "good":
return Color.LIME;
default:
return Color.WHITESMOKE;
}
}
TableView<Item> table = new TableView<>(FXCollections.observableArrayList(
new Item("ok"),
new Item("bad"),
new Item("good")));
TableColumn<Item, String> typeColumn = new TableColumn<>("type");
typeColumn.setCellValueFactory(new PropertyValueFactory<>("type"));
table.setRowFactory(tv -> {
TableRow<Item> row = new TableRow<>();
StringBinding typeBinding = Bindings.selectString(row.itemProperty(), "type");
row.backgroundProperty().bind(Bindings.createObjectBinding(()
-> new Background(new BackgroundFill(typeToColor(typeBinding.get()), CornerRadii.EMPTY, Insets.EMPTY)), typeBinding));
return row;
});
table.getColumns().add(typeColumn);
Finally I have done this thing:
Callback<TableColumn<CustomerObj, String>, TableCell<CustomerObj, String>> cellFactory
= new Callback<TableColumn<CustomerObj, String>, TableCell<CustomerObj, String>>() {
public TableCell call(TableColumn p) {
TableCell cell = new TableCell<CustomerObj, String>() {
#Override
public void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (!empty) {
CustomerObj obj = this.getTableView().getItems().get(getIndex());
setText(obj.getType());
switch (obj.getType()) {
case "good":
setStyle("-fx-background-color: rgba(71, 209, 71, .7)");
break;
case "problem":
setStyle("-fx-background-color: rgba(255, 51, 51, .7)");
break;
case "ViP":
setStyle("-fx-background-color: rgba(255, 219, 25 .7)");
break;
default:
break;
}
} else {
setText(null);
}
}
private String getString() {
return getItem() == null ? "" : getItem().toString();
}
};
return cell;
}
};
colType.setCellFactory(cellFactory);
Works fine and looks so much better, but thanks it brought me closer to the solution.
Related
Helper Class
public class HomeScreenChatsHelper implements Comparable {
private String ID;
private String Name;
private String Image;
private String From;
private String Seen;
private String LastMessage;
private String LastMessageTime;
public HomeScreenChatsHelper(){
}
public HomeScreenChatsHelper(String id, String name, String image, String from, String seen, String lastmessage, String lastMessageTime) {
this.ID=id;
this.Name = name;
this.Image = image;
this.From = from;
this.Seen = seen;
this.LastMessage = lastmessage;
this.LastMessageTime = lastMessageTime;
}
public String getID() {
return ID;
}
public void setID(String id) {
ID = id;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getImage() {
return Image;
}
public void setImage(String image) {
Image = image;
}
public String getMessage() {
return LastMessage;
}
public void setMessage(String message) {
LastMessage = message;
}
public String getTime() {
return LastMessageTime;
}
public void setTime(String time) {
LastMessageTime = time;
}
public String getFrom() {
return From;
}
public void setFrom(String from) {
From = from;
}
public String getSeen() {
return Seen;
}
public void setSeen(String seen) {
Seen = seen;
}
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public int compareTo(Object comparestu) {
long compareage= Long.parseLong(((HomeScreenChatsHelper)comparestu).getTime());
long a = Long.parseLong(LastMessageTime);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
}
return Long.compare(a,compareage);
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof HomeScreenChatsHelper)) return false;
HomeScreenChatsHelper that = (HomeScreenChatsHelper) o;
return getID().equals(that.getID());
}
#Override
public int hashCode() {
return getID().hashCode();
}
Activity
for(HomeScreenChatsHelper str : mChats) {
if (str.getID().equals(ID)) {
mChats.remove(ID);
break;
}
}
There are a ton of tutorials on how to do it and I've spent the past week looking for a solution and I still don't have it. Is there anyway I can remove an whole object by just specifying just the ID? I wont have the values of all the other fields so I just want to remove a particular object by its ID. Also I cant use the clear option because I need the other data. So can someone help me out please?
With the present code nothing happens. No errors but doesn't work
By using java-8 you can filter the list, result will be the List<HomeScreenChatsHelper> that does have HomeScreenChatsHelper with same id
List<HomeScreenChatsHelper> mChats = new ArrayList<>();
//filter
List<HomeScreenChatsHelper> result = mChats.stream()
.filter(str->!str.getId().equals(Id)).
.collect(Collectors.toList());
Or by using Iterator
// Iterator.remove()
Iterator itr = mChats.iterator();
while (itr.hasNext())
{
HomeScreenChatsHelper x = itr.next();
if (x.getId().equals(Id)) }
itr.remove();
}
}
Your question is quite unclear. is mChats a List containing HomeScreenChatsHelper objects?
I assume so. If this is the case, then you can change your foreach loop into the normal loop
//Assuming mChats is List e.g ArrayList
for (int i = 0; mChats.size(); i++){
if (mChats.get(i).getID().equals(ID)) {
mChats.remove(i);
break;
}
}
The easiest way in Java 8 or later is with Collection#removeIf:
mChats.removeIf(str -> str.getID().equals(ID));
By the way, the convention in Java is for fields to begin with a lowercase letter.
I have a Navigation class where I am dynamically creating the navigation I am having two tables folder(it is directory that contains files) and content(it is like files or pages that will render the content on the public site). I have created a Navigation class in which I am having a wrapper class for merging the fields of content into the folder. I have tried using #OrderBy and #OrderColumn but I came to know that it will only work with collections.
List<Folder> folder = folderRepository.findAllByNavDepthLessThanOrderByNavDepthAsc(3);
here I am sorting it with navDepth(this column belongs to Folder entity) I also want to sort it with navOrder(this column belongs to Content entity)
#Service
public class NavigationService {
#Qualifier("jdbcMySQL")
private JdbcTemplate jdbcTemplate;
private FolderRepository folderRepository;
private FolderService folderService;
#Autowired
public NavigationService(JdbcTemplate jdbcTemplate,
FolderRepository folderRepository,
FolderService folderService) {
this.jdbcTemplate = jdbcTemplate;
this.folderRepository = folderRepository;
this.folderService = folderService;
}
#Transactional(propagation=Propagation.REQUIRED, readOnly=false)
public Map<String, NavigationItem> navigationItems() {
// TODO: // CROSS cutting AOP springs
// TODO: http://docs.spring.io/spring/docs/4.2.0.BUILD-SNAPSHOT/spring-framework-reference/htmlsingle/#aop
List<Folder> folder = folderRepository.findAllByNavDepthLessThanOrderByNavDepthAsc(3);
// List<Folder> folder = folderService.navigation();
Map<String, NavigationItem> navItems = new LinkedHashMap<String, NavigationService.NavigationItem>();
for (int i = 0; i < folder.size(); i++) {
NavigationItem ni = new NavigationItem();
ni.setNavDepth((int) (folder.get(i).getNavDepth()));
ni.setFileNamePath(folder.get(i).getDirectoryPath());
ni.setFilepath(folder.get(i).getDirectoryPath());
ni.setChildren(folder.get(i).getContent());
for (int k = 0; k < folder.size(); k++) {
if(folder.get(i).getId() == folder.get(k).getParentId()) {
ni.addSubFolder(folder.get(k));
System.out.println(folder.get(i).getTitle());
System.out.println(folder.get(k));
System.out.println("---!!!!!!________----------!!!!!!!!");
}
}
navItems.put(folder.get(i).getTitle(), ni);
}
return navItems;
}
public class NavigationItem {
private long id;
private long parentId;
private String title;
private String fileName;
private String fileNamePath;
private int navDepth;
private int navOrder;
private String parentFileName;
private String filePath;
private String folderName;
#OrderColumn(name="navOrder ASC")
private List<Content> children = new ArrayList();
private ArrayList<Folder> subFolder = new ArrayList();
public void setSubFolder(ArrayList<Folder> subFolder) {
this.subFolder = subFolder;
}
public String getFilePath() {
return filePath;
}
public void setFilePath(String filePath) {
this.filePath = filePath;
}
public String getFolderName() {
return folderName;
}
public void setFolderName(String folderName) {
this.folderName = folderName;
}
public ArrayList<Folder> getSubFolder() {
return subFolder;
}
public void addSubFolder(Folder subFolder) {
this.subFolder.add(subFolder);
}
public void setChildren(List<Content> list) {
this.children = list;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public long getParentId() {
return parentId;
}
public void setParentId(long parentId) {
this.parentId = parentId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getFileNamePath() {
return fileNamePath;
}
public void setFileNamePath(String fileNamePath) {
this.fileNamePath = fileNamePath;
}
public long getNavDepth() {
return navDepth;
}
public void setNavDepth(int navDepth) {
this.navDepth = navDepth;
}
public long getNavOrder() {
return navOrder;
}
public void setNavOrder(int navOrder) {
this.navOrder = navOrder;
}
public String getParentFileName() {
return parentFileName;
}
public void setParentFileName(String parentFileName) {
this.parentFileName = parentFileName;
}
public List<Content> getChildren() {
return children;
}
public void addChild(Content child) {
children.add(child);
}
public String getFilepath() {
return filePath;
}
public void setFilepath(String filePath) {
this.filePath = filePath;
}
}
}
Use a Comparator<NavigationItem> and pass that to Collections.sort() or similar methods.
The comparator might look like this:
class NavComparator implements Comparator<NavigationItem> {
int specialValueNoChildren = -1; //assuming nav_order is always 0 or greater
int compare(NavigationItem o1, NavigationItem o2) {
int max1 = getMaxNavOrder( o1 );
int max2 = getMaxNavOrder( o2 );
return Integer.compare( max1, max2 );
}
int getMaxNavOrder( NavigationItem ni ) {
int max = specialValueNoChildren;
for( Content child : ni.getChildren() ) {
max = Math.max(max, child.getNavOrder());
}
return max;
}
}
Here the maximum nav order of all children is selected with -1 being the special case of no children. Then the items are compared by their respective children's maximum nav order.
If you need a different order change that accordingly, e.g. by reversing max1 and max2 or by getting the lowest nav order of the children etc.
Hello I have got a question about TableView in JavaFX and populating the table with data from an object in the model via a getter method of this object, which is part of the model .
First of all, here is my model:
package model;
import java.util.List;
public class Carmodel {
private int carmodelID;
private Cartype cartype;
private Manufacturer manufacturer;
private DrivingLicense drivingLicense;
private String label;
private int seats;
private int kw;
private String fuelType;
private double priceDay;
private double priceKM;
private int axes;
private int loadVolume;
private int loadCapacity;
private List<Equipment> equipmentList;
public Carmodel() {
}
public int getCarmodelID() {
return carmodelID;
}
public void setCarmodelID(int carmodelID) {
this.carmodelID = carmodelID;
}
public Cartype getCartype() {
return cartype;
}
public void setCartype(Cartype cartype) {
this.cartype = cartype;
}
public Manufacturer getManufacturer() {
return manufacturer;
}
public void setManufacturer(Manufacturer manufacturer) {
this.manufacturer = manufacturer;
}
public DrivingLicense getDrivingLicense() {
return drivingLicense;
}
public void setDrivingLicense(DrivingLicense drivingLicense) {
this.drivingLicense = drivingLicense;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public int getSeats() {
return seats;
}
public void setSeats(int seats) {
this.seats = seats;
}
public int getKw() {
return kw;
}
public void setKw(int kw) {
this.kw = kw;
}
public String getFuelType() {
return fuelType;
}
public void setFuelType(String fuelType) {
this.fuelType = fuelType;
}
public double getPriceDay() {
return priceDay;
}
public void setPriceDay(double priceDay) {
this.priceDay = priceDay;
}
public double getPriceKM() {
return priceKM;
}
public void setPriceKM(double priceKM) {
this.priceKM = priceKM;
}
public int getAxes() {
return axes;
}
public void setAxes(int axes) {
this.axes = axes;
}
public int getLoadVolume() {
return loadVolume;
}
public void setLoadVolume(int loadVolume) {
this.loadVolume = loadVolume;
}
public int getLoadCapacity() {
return loadCapacity;
}
public void setLoadCapacity(int loadCapacity) {
this.loadCapacity = loadCapacity;
}
public List<Equipment> getEquipmentList() {
return equipmentList;
}
public void setEquipmentList(List<Equipment> equipmentList) {
this.equipmentList = equipmentList;
}
As you can see there is a specific member (private Manufacturer manufacturer) It is an object from the type "Manufacturer". And the Manufacturer class looks like this:
public class Manufacturer {
private int manufacturerID;
private String name;
public Manufacturer() {
}
public int getManufacturerID() {
return manufacturerID;
}
public void setManufacturerID(int manufacturerID) {
this.manufacturerID = manufacturerID;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
This is my controller for the JavaFX View:
public class CarmodelController implements Initializable {
CarmodelRepository carmodelRepository;
#FXML public TableView CarmodelTable;
#FXML public TableColumn<Carmodel,Integer> tableColumnID ;
#FXML public TableColumn<Carmodel,String> tableColumnLabel ;
#FXML public TableColumn<Carmodel, String> tableColumnManufacturer ;
#FXML public TableColumn<Carmodel,String> tableColumnCartype ;
public void initialize(URL location, ResourceBundle resources) {
carmodelRepository= new CarmodelRepository();
List<Carmodel> carmodelList= carmodelRepository.readAll();
ObservableList<Carmodel> carmodelObservableList = FXCollections.observableArrayList(carmodelList);
tableColumnID.setCellValueFactory(new PropertyValueFactory<Carmodel, Integer>("carmodelID"));
tableColumnLabel.setCellValueFactory(new PropertyValueFactory<Carmodel, String>("label"));
tableColumnManufacturer.setCellValueFactory(new PropertyValueFactory<Carmodel, String>("manufacturer")
And here is the problem:
Can I do here something like PropertyValueFactory("manufacturer.getName()"); This way it didn't work. It just populate the column of the table with memory adress
So my question is:
How can I get the name of the manufacturer, normally, in other code, you can do this by calling the method: "manufacturer.getName();" and it will give you the String with the name of the manufacturer, but how can I do this while I will populate the table with these specific carmodels?
And the end of the controller code ( filling the Table with values).
CarmodelTable.setItems(carmodelObservableList);
}
Thank you in advance!
You can do
tableColumnManufacturer.setCellValueFactory(cellData ->
new ReadOnlyStringWrapper(cellData.getValue().getManufacturer().getName());
The setCellValueFactory method expects a Callback<CellDataFeatures<Carmodel, String>, ObservableValue<String>> object. Hence cellData in this code is a CellDataFeatures<Carmodel, String> object, and cellData.getValue() gives the CarModel object for the row. Then cellData.getValue().getManufacturer().getName() gives the value you want; you just have to wrap it in a ReadOnlyObservableWrapper to get an ObservableValue<String> containing that value.
I have a question about the handling of node properties in an outlineview.
I have three level of nodes, the rootNode, the node and each node may have sub-nodes. Apart from the rootNode, all nodes and subnodes shall have the same (Boolean => checkbox) property. In my outlineview I have two columns, the node(s) column, and a property column with checkboxes.
What I need now is the behaviour, that when I activate the checkbox of a node, all its sub-nodes checkboxes shall be activated as well, when I deactivate the checkbox of a node, all its sub-nodes checkboxes shall be de-activated as well. If I expand the tree to see the sub-nodes, each sub-node may be selected as well.
My current code looks like the following (some parts are found on the internet):
The main api
public class Category {
private String name;
private Boolean x;
public Category() {
this("empty");
}
public Category(String name) {
this.name = name;
}
public Category(String name, Boolean x) {
this.name = name;
this.x = x;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Boolean getx() {
return x;
}
public void setx(Boolean x) {
this.x = x;
}
}
My ChildFactory for the nodes (category) looks like
public class CategoryChildrenFactory extends ChildFactory.Detachable<Category> {
/* detachable has no real effect on the current code, used to control
the life cylce */
#Override
protected boolean createKeys(List<Category> toPopulate) {
toPopulate.add(new Category("Cat1", false));
toPopulate.add(new Category("Cat2", false));
toPopulate.add(new Category("Cat3", false));
return true;
}
#Override
protected Node createNodeForKey(Category key) {
AllNode cn = new AllNode(key);
return cn;
}
}
and for the sub-nodes
public class MovieChildrenFactory extends ChildFactory<String>{
Category category;
public MovieChildrenFactory(Category category) {
this.category = category;
}
#Override
protected boolean createKeys(List<String> toPopulate) {
toPopulate.add("m_1");
toPopulate.add("m_2");
toPopulate.add("m_3");
return true;
}
#Override
protected Node createNodeForKey(String key) {
return new AllNode(category, key);
}
}
The nodes creation is put into a single class for both types (nodes, subnodes)
public class AllNode extends AbstractNode {
Category category;
String title;
private Sheet.Set set;
public AllNode(Category category) {
this(category, null);
this.category = category;
set = Sheet.createPropertiesSet();
}
public AllNode(Category category, String title) {
super(Children.LEAF, Lookups.singleton(category));
if (title == null) {
this.setChildren(Children.create(new MovieChildrenFactory(category), true));
}
this.title = title;
set = Sheet.createPropertiesSet();
}
#Override
public String getHtmlDisplayName() {
String name = "";
if (title == null) {
name = category.getName();
} else {
name = title;
}
return name;
}
#Override
protected Sheet createSheet() {
Sheet sheet = Sheet.createDefault();
Category obj = getLookup().lookup(Category.class);
PlotMathProperties pmp = new PlotMathProperties(obj, title);
set.put(pmp.getMyProperty());
sheet.put(set);
return sheet;
}
}
The properties are handled by
public class PlotMathProperties {
private MyProperty myProperty;
private String categoryName;
private String title;
public PlotMathProperties(Category category, String title) {
this.categoryName = category.getName();
this.title= title;
this.myProperty= new MyProperty ();
}
public XProperty getMyProperty () {
return myProperty;
}
public class MyProperty extends PropertySupport.ReadWrite<Boolean> {
private Boolean isMyProp = false;
public MyProperty () {
super("x", Boolean.class, "XPROP", "Is this a coloured or black and white movie");
}
#Override
public Boolean getValue() throws IllegalAccessException, InvocationTargetException {
return isMyProp ;
}
#Override
public void setValue(Boolean val) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
isMyProp = val;
if (isMyProp) {
System.out.println("active: " + categoryName + ", " + title);
} else {
System.out.println("de-active: " + categoryName + ", " + title);
}
}
}
}
Together with a TopComponent the outlineview looks nice and works well.
Has anyone an idea how to setup the the behaviour for the check-boxes
regards
I have a DropDownChoice :
DropDownChoice timePeriod = new DropDownChoice("timePeriod", Arrays.asList(new TimePeriod(1, "Weekly"), new TimePeriod(2, "Bi-Weekly"), new TimePeriod(3, "Semi-Monthly"), new TimePeriod(4, "Monthly"), new TimePeriod(5, "Yearly")), new IChoiceRenderer() {
private static final long serialVersionUID = 10102L;
#Override
public String getIdValue(Object object, int index) {
return ((TimePeriod) object).getId() + "";
}
#Override
public Object getDisplayValue(Object object) {
return ((TimePeriod) object).getPeriodType();
}
});
timePeriod.setNullValid(false);
My question is:
How to set the selected index to 2 or any other?
How to remove first default blank option?
Thank you.
You should be able to set the selected index by using a PropertyModel instead of hard-coding the values of the dropdown. I can't test at the moment, but it would be something like
String timePeriodValue = "Bi-Weekly";
DropDownChoice timePeriod = new DropDownChoice("timePeriod",
new PropertyModel(this, "timePeriodValue"),
Arrays.asList(/* your options */),
new IChoiceRenderer() {
// ...
// Again, this is pseudocode only
As a bonus, the very act of setting a default value should eliminate the blank option problem.
DropDownChoice has a constructor which accepts the default value.
Or in your code you can add timePeriod.setModel(Model.of(new TimePeriod(2, "Bi-Weekly")))
I guess TimePeriod has proper #equals() and #hashCode() implementations.
About the blank option: see org.apache.wicket.markup.html.form.AbstractSingleSelectChoice.isNullValid()
Lord Torgamus and martin-g thank you both of you. I did a small test. And it is working perfectly. As Lord Torgamus indicated,
#SuppressWarnings({ "unchecked", "rawtypes", "serial" })
public class MyPage extends WebPage {
public MyPage() {
add(new MyForm("form"));
}
private class MyForm extends Form {
public MyForm(String id) {
super(id);
setOutputMarkupPlaceholderTag(true);
setModel(new Model(new FormModel()));
final DropDownChoice timePeriod = new DropDownChoice("timePeriod", new PropertyModel(getModel(), "timePeriod"), Arrays.asList(new TimePeriod(1, "Weekly"), new TimePeriod(2, "Bi-Weekly"), new TimePeriod(3, "Semi-Monthly"), new TimePeriod(4, "Monthly"), new TimePeriod(5, "Yearly")), new IChoiceRenderer() {
private static final long serialVersionUID = 10102L;
#Override
public String getIdValue(Object object, int index) {
return ((TimePeriod) object).getId() + "";
}
#Override
public Object getDisplayValue(Object object) {
return ((TimePeriod) object).getPeriodType();
}
});
timePeriod.setNullValid(false);
add(timePeriod);
timePeriod.setOutputMarkupPlaceholderTag(true);
timePeriod.add(new AjaxFormComponentUpdatingBehavior("onChange") {
#Override
protected void onUpdate(AjaxRequestTarget target) {
MyForm form = (MyForm) timePeriod.getParent();
FormModel formModel = (FormModel) form.getModelObject();
formModel.setTimePeriod(new TimePeriod(4, "Monthly"));
form.setModel(new Model(formModel));
target.addComponent(form);
}
});
}
#Override
public void onSubmit() {
System.out.println(getModelObject());
}
}
private class FormModel implements Serializable {
private TimePeriod timePeriod = new TimePeriod(2, "Bi-Weekly");
public FormModel() {
}
public TimePeriod getTimePeriod() {
return timePeriod;
}
public void setTimePeriod(TimePeriod timePeriod) {
this.timePeriod = timePeriod;
}
#Override
public String toString() {
return "FormModel [timePeriod=" + timePeriod + "]";
}
}
private class TimePeriod implements Serializable {
private int id;
private String periodType;
public TimePeriod(int id, String periodType) {
super();
this.id = id;
this.periodType = periodType;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPeriodType() {
return periodType;
}
public void setPeriodType(String periodType) {
this.periodType = periodType;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + getOuterType().hashCode();
result = prime * result + id;
result = prime * result + ((periodType == null) ? 0 : periodType.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
TimePeriod other = (TimePeriod) obj;
if (!getOuterType().equals(other.getOuterType()))
return false;
if (id != other.id)
return false;
if (periodType == null) {
if (other.periodType != null)
return false;
} else if (!periodType.equals(other.periodType))
return false;
return true;
}
private LoginPage getOuterType() {
return LoginPage.this;
}
#Override
public String toString() {
return "TimePeriod [id=" + id + ", periodType=" + periodType + "]";
}
}
}
The above code is provided for other users as it might be helpful and I wrote it for testing purpose so all the classes are written in one .java file although it is not advisable.
Thank you.