can't find the way to bind a vaadin combobox - java

my problem is that I can't find the way to bind a combobox, my goal is to autocomplete a combobox after clicking on a table (Grid):
The combobox data is taken from the BD Acception table, but the table data is taken from the WordAcception class
These are the errors it shows me:
[enter image description here][1]
[enter image description here][2]
WORDACCEPTION.java
public class WordAcception implements Serializable, Cloneable {
private String idacception = "";
public String getIdacception() {
return idacception;
}
public void setIdacception(String idacception) {
this.idacception = idacception;
}
}
VISTA.java
private ComboBox<Acception> WordAcceptioncombo = new ComboBox<>("idacception");
WordAcceptioncombo.setItemLabelGenerator(Acception::getIdAcception);
WordAcceptioncombo.setItems(AcceptionPersistence.getInstance().findAllIdAcception());
add(WordAcceptioncombo);
wordacceptionGrid.asSingleSelect().addValueChangeListener(event ->
formword.setWordAcception(wordacceptionGrid.asSingleSelect().getValue()));
WORDACCEPTIONFORM.java
binder.bind(WordAcceptioncombo, Acception::getIdAcception,
Acception::setIdAcception);
public void setWordAcception(WordAcception wordAcception) {
if(wordAcception != null) {
System.out.println("setWordAcception= "+wordAcception.getIdacception());
WordAcceptioncombo.setValue(wordAcception.getIdacception());
}
binder.setBean(wordAcception);
if (binder.getBean() == null) {
setVisible(false);
} else {
setVisible(true);
idacception.focus();
}
}
Aception.java
public class Acception implements Serializable, Cloneable {
private String idAcception = "";
public String getIdAcception() {
return idAcception;
}
public void setIdAcception(String idAcception) {
this.idAcception = idAcception;
}
}
/////////////UPDATE///////////
The combobox is completed thanks to the Acception class, for that reason I had to create an Acception instance in the WordAcception class in order to obtain that instance of the class (this has hidden the problems from me, but the combobox still does not autofill)
ACCEPTION.JAVA
public class Acception implements Serializable, Cloneable {
private Clase clase;
public Clase getClase() {
return clase;
}
public void setClase(Clase clase) {
this.clase = clase;
}
WORDACCEPTIONFORM.JAVA
binder.bind(WordAcceptioncombo, WordAcception::getAcception,
WordAcception::setAcception);
BUT I DON'T NOTICE ANY CHANGE, THE COMBOBOX STILL NOT FILLED

You usually get that kind of is not applicable for the arguments error from .bind when you are using a getter and setter for a value that is a different type than your field. In your case WordAcception.idAcception is type String but your ComboBox is set to take in items of type Acception.
If you want a ComboBox that gives you the option of selecting which particular id belongs to this specific WordAcception and for changing that id (without changing the WordAcception instance), the type of the ComboBox should be String. If you want a ComboBox that selects a specific Acception for you, you need to use a getter and setter for a field of that type.
Unrelated to the error, I'm not quite certain if there is supposed to be some connection between Acception and WordAcception, but based on the examples currently there is none. Did you mean for one of them to extend the other?

Related

wicket models is not updated

I have a Link in the constructor of the class DetailsPanel and I want it to save a change in the form of the class DetailsPanel when I click on it and go to the next page.
When I use for example if(propertyModel.getSomething() != null) { // change something } in the constructor Details() the change is made.
When I do the same in the constructor DetailsPanel() that is if(info.getSomething() != null) { // change something } the change is not made because the model is not updated when I click the link. It just goes to the next page and when I go back the change does not remain..
I have tested the code and the value of "something" passes in both cases.
I am just trying to understand how the wicket model works here...
public class DetailsPanel extends Panel {
private static final class Details extends BootstrapForm<InfoModel> {
public Details(String id, final CompoundPropertyModel<InfoModel> propertyModel) {
// form with various components..
}
}
public DetailsPanel(String id, final InfoModel info) {
// my link is here
}
}
public class InfoModel implements IClusterable {
// private fields with getters and setters eg.
private int something;
}

Putting data in a TableView [duplicate]

This has baffled me for a while now and I cannot seem to get the grasp of it. I'm using Cell Value Factory to populate a simple one column table and it does not populate in the table.
It does and I click the rows that are populated but I do not see any values in them- in this case String values. [I just edited this to make it clearer]
I have a different project under which it works under the same kind of data model. What am I doing wrong?
Here's the code. The commented code at the end seems to work though. I've checked to see if the usual mistakes- creating a new column instance or a new tableview instance, are there. Nothing. Please help!
//Simple Data Model
Stock.java
public class Stock {
private SimpleStringProperty stockTicker;
public Stock(String stockTicker) {
this.stockTicker = new SimpleStringProperty(stockTicker);
}
public String getstockTicker() {
return stockTicker.get();
}
public void setstockTicker(String stockticker) {
stockTicker.set(stockticker);
}
}
//Controller class
MainGuiController.java
private ObservableList<Stock> data;
#FXML
private TableView<Stock> stockTableView;// = new TableView<>(data);
#FXML
private TableColumn<Stock, String> tickerCol;
private void setTickersToCol() {
try {
Statement stmt = conn.createStatement();//conn is defined and works
ResultSet rsltset = stmt.executeQuery("SELECT ticker FROM tickerlist order by ticker");
data = FXCollections.observableArrayList();
Stock stockInstance;
while (rsltset.next()) {
stockInstance = new Stock(rsltset.getString(1).toUpperCase());
data.add(stockInstance);
}
} catch (SQLException ex) {
Logger.getLogger(WriteToFile.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("Connection Failed! Check output console");
}
tickerCol.setCellValueFactory(new PropertyValueFactory<Stock,String>("stockTicker"));
stockTableView.setItems(data);
}
/*THIS, ON THE OTHER HAND, WORKS*/
/*Callback<CellDataFeatures<Stock, String>, ObservableValue<String>> cellDataFeat =
new Callback<CellDataFeatures<Stock, String>, ObservableValue<String>>() {
#Override
public ObservableValue<String> call(CellDataFeatures<Stock, String> p) {
return new SimpleStringProperty(p.getValue().getstockTicker());
}
};*/
Suggested solution (use a Lambda, not a PropertyValueFactory)
Instead of:
aColumn.setCellValueFactory(new PropertyValueFactory<Appointment,LocalDate>("date"));
Write:
aColumn.setCellValueFactory(cellData -> cellData.getValue().dateProperty());
For more information, see this answer:
Java: setCellValuefactory; Lambda vs. PropertyValueFactory; advantages/disadvantages
Solution using PropertyValueFactory
The lambda solution outlined above is preferred, but if you wish to use PropertyValueFactory, this alternate solution provides information on that.
How to Fix It
The case of your getter and setter methods are wrong.
getstockTicker should be getStockTicker
setstockTicker should be setStockTicker
Some Background Information
Your PropertyValueFactory remains the same with:
new PropertyValueFactory<Stock,String>("stockTicker")
The naming convention will seem more obvious when you also add a property accessor to your Stock class:
public class Stock {
private SimpleStringProperty stockTicker;
public Stock(String stockTicker) {
this.stockTicker = new SimpleStringProperty(stockTicker);
}
public String getStockTicker() {
return stockTicker.get();
}
public void setStockTicker(String stockticker) {
stockTicker.set(stockticker);
}
public StringProperty stockTickerProperty() {
return stockTicker;
}
}
The PropertyValueFactory uses reflection to find the relevant accessors (these should be public). First, it will try to use the stockTickerProperty accessor and, if that is not present fall back to getters and setters. Providing a property accessor is recommended as then you will automatically enable your table to observe the property in the underlying model, dynamically updating its data as the underlying model changes.
put the Getter and Setter method in you data class for all the elements.

checking type of reference in generics java

I am currently building a game in java(turn based RPG) and am facing a problem in inventory UI. Perhaps my problem is well known or has a simple solution, but having never had any training, I will still ask the question.
While displaying the inventory after selecting an item I check if that item implements the SpecificItemWorker interface , that is, acts on a specific GameObject that has to be passed in to its takeAction() method. While selecting that object which has to be passed, I display all the possible candidate objects for the user to select. For example, suppose the user selects a UpgradeParchment that acts on any object that implements Upgradable interface. Here, I initiate a ItemSelector that displays all the items in the inventory that implements Upgradable. However with a different class , the interface that the object needs to implement in order to be a possible candidate will differ.(Note that some objects act on the game environment rather than on a specific object, but we are not considering that case here.).Now instead of hard-coding the possible interfaces in a switch case statement , i want it to be dynamic.I tried to use generics, but it does not allow to check if an object is an instanceof of the Type parameter.
The following code gives a compile error:
package ui;
import objects.Collectable;
public class ItemSelector<T> {
public void test(Collectable ob) {
if (ob instanceof T) {// compile error
// do work
}
}
}
Does anyone know how this can be achieved?Thanks for any help.
Looking for a speedy reply,
Thanks.
EDIT :
The parameter in the testAction() method will be of type Collectable as in my inventory class, there is only a list of Collectable objects.Similarly, in my test method , I have updated the types.Although it is a minor change, sorry for any inconvenience.Collectable is also an interface.
Due to runtime type erasure, you need to provide what's called a type token to the class:
public class ItemSelector<T> {
private final Class<T> clazz;
public ItemSelector(Class<T> clazz) {
this.clazz = clazz;
}
public void test(GameObject ob) {
if (clazz.isInstance(ob)) {// use token to check type
// do work
}
}
}
This requires a class object to be passed to the constructor, usually by passing a class literal, eg MyClass.class
There is a way to check the type with class.getTypeName().
I assume the SpecificItemWorker is a game object as shown in the code.
package stackoverflow.question39718130;
public class SpecificItemWorker extends GameObject {
}
package stackoverflow.question39718130;
public class ItemSelector<T> {
private T t;
public ItemSelector(final T t) {
this.t = t;
}
public T getT() {
return t;
}
public void test(final GameObject ob) {
/*if (ob instanceof T) {// compile error
// do work
}*/
if (t.getClass().getTypeName() == ob.getClass().getTypeName()) {
System.out.println("Grab item.");
} else {
System.err.println("No item found.");
}
}
}
There is a test example to pass the GameObject.
package stackoverflow.question39718130;
public class GameObjectTest {
public static void main(final String[] args) {
specificItemWorkerTest();
}
public static void specificItemWorkerTest() {
final GameObject specificItemWorker = new SpecificItemWorker();
final ItemSelector<GameObject> selector = new ItemSelector<>(specificItemWorker);
selector.test(specificItemWorker);
}
}
I hope I understood you right with the SpecificItemWorker. Please let me know if this fits to your solution.

Adding an item to an indexed property - PropertyChangeSupport

I am currently working with PropertyChangeListeners and I want to know if it would be advisable to fire a property change whenever an object is added (or removed, for that matter) to an indexed property such as an ArrayList.
public class SimpleBean implements Serializable
{
private ArrayList<Matrix> mats;
private PropertyChangeSupport pcs = new PropertyChangeSupport(this);
public SimpleBean()
{...}
public void addMat(Matrix m)
{
pcs.firePropertyChange("mats", null, m); // I'm having trouble with the parameters
mats.add(m);
}
}
I was reading the PropertyChangeListener tutorials and it seemed like it was appropriate to fire a property change whenever the value of a bound property changed. Well, I wasn't quite sure if this meant that I should fire a property change whenever a property was modified by any means or only when the property (or an element of that property) was strictly set/reassigned to a different value.
In my program, it would be very convenient if several classes could change every time an element is removed from or added to the mats ArrayList, and I figured that a PropertyChangeListener could help me in that regard.
Please let me know if this method is not recommended and if there is another way that other classes can listen and respond to deletion/addition to indexed properties.
See the following example:
public class SimpleBean implements Serializable {
private ArrayList<Matrix> mats;
private PropertyChangeSupport pcs = new PropertyChangeSupport(this);
public void setMats(ArrayList<Matrix> mats) {
if(mats.equals(this.mats))
return;
ArrayList<Matrix> oldMats = this.mats ;
this.mats = mats ;
pcs.firePropertyChange("mats", oldMats, mats);
}
public ArrayList<Matrix> getMats() {
return mats;
}
public void setMat(int index, Matrix mat) {
Matrix existing = index == mats.size() ? null : mats.get(index);
if(existing.equals(mat))
return;
mats.remove(index);
mats.add(index, mat);
pcs.fireIndexedPropertyChange("mats", index, existing, mat);
}
public Matrix getMat(int index) {
return mats.get(index);
}
public void addMat(Matrix m) {
setMat(mats.size(), m);
}
}
Which implements both propertyChange as well as indexedPropertyChange for mats.

Set the list of acceptable values in a GWT ValueListBox based on an EnumSet?

Given that I have this entity as part of an editor chain:
public class Commission implements Serializable
{
private EnumSet<CommissionType> commissionTypes;
private CommissionType type; // must exist in commissionTypes
private String value;
public Commission()
{
}
}
and this editor for it:
public class CommissionEditor extends Composite implements Editor<Commission>
{
private static CommissionEditorUiBinder uiBinder = GWT.create(CommissionEditorUiBinder.class);
interface CommissionEditorUiBinder extends UiBinder<Widget, CommissionEditor>
{
}
#UiField(provided = true)
ValueListBox<CommissionType> type = new ValueListBox<CommissionType>(new AbstractRenderer<CommissionType>()
{
#Override
public String render(CommissionType object)
{
return object == null ? "" : object.toString();
}
});
#UiField
TextBox value;
public CommissionEditor()
{
type.setAcceptableValues(Arrays.asList(CommissionType.values()));
initWidget(uiBinder.createAndBindUi(this));
}
}
At the moment the ValueListBox renders all possible options for CommissionType, like this:
The EnumSet could contain between 1 and 4 of the possible options, depending on the particular entity. Is there a way to make the ValueListBox only render the options in the EnumSet and then save the value in commissionType?
Bear in mind that I want to set the value of commissionType as well.
There are two ways to solve it:
1.) If you have a direct access to the CommissionEditor then create a setter in it call it when you edit the entity:
public void setAcceptableValues(List<CommissionType> values) {
type.setAcceptableValues(values);
}
And call it like this when you call driver.edit(entity);:
commissionEditor.setAcceptableValues(commission.getCommissionTypes());
2.) Instead of extending the Editor interface you can extend the ValueAwareEditor and in the setValue() method call setAcceptableValues with the corresponding values.
Approach 2 is probably the cleaner approach.

Categories

Resources