javafx2 tableview issue : callback and editable combobox in cell - combobox

I have an issue with a tableview and its cells. I want to customize a cell with an editable combobox. Here my code of the combobox :
public class CbbxEditSuppr extends ComboBox<BoxItem> {
private TextField editor = null;
private ObservableList<BoxItem> items = null;
private double prefWidth = 0.0;
/**
* Constructeur.
*
* #param addedItems ObservableList<String>
* #param prefWidth double largeur préférée
*/
public CbbxEditSuppr(ObservableList<String> addedItems, final double prefWidth) {
// initialisation des attributs
editor = this.getEditor();
items = this.getItems();
this.prefWidth = prefWidth;
this.setPrefWidth(prefWidth);
// initialisation du contenu de la cellule
this.setCellFactory(new Callback<ListView<BoxItem>, ListCell<BoxItem>>() {
#Override
public ListCell<BoxItem> call(ListView<BoxItem> p) {
final ListCell<BoxItem> cell = new ListCell<BoxItem>() {
#Override
protected void updateItem(BoxItem t, boolean bln) {
super.updateItem(t, bln);
if (t != null) {
setGraphic(t);
} else {
setGraphic(null);
}
}
};
return cell;
}
});
// déininition du converter
this.setConverter(new StringConverter<BoxItem>() {
#Override
public String toString(BoxItem cbbx) {
if (cbbx == null) {
return null;
} else {
return cbbx.getName();
}
}
#Override
public BoxItem fromString(String id) {
if (id != null) {
final BoxItem box = new BoxItem(id, items, prefWidth);
return box;
} else {
return null;
}
}
});
/* ajout des valeurs a la liste d'items */
if (addedItems != null && addedItems.size() > 0) {
for (String stg : addedItems) {
if (stg != null) {
final BoxItem hbox = new BoxItem(stg, items, this.prefWidth);
items.add(hbox);
}
}
}
// permet de prendre en compte la touche ENTER, et ajouter des valeurs a la liste
this.addEventFilter(KeyEvent.KEY_PRESSED, new EventHandler<KeyEvent>() {
public void handle(final KeyEvent event) {
if (event != null && event.getCode().equals(KeyCode.ENTER)) {
if (editor.getText().trim().length() > 0) {
addItem(editor.getText(), prefWidth);
editor.clear();
}
}
}
});
// propriétés editable et selection du premier element
this.setEditable(true);
this.getSelectionModel().selectFirst();
// ajout de l'affichage du menu popup lors du focus du textfield d'edition de la combobox
editor.focusedProperty().addListener(new ChangeListener<Boolean>() {
#Override
public void changed(ObservableValue<? extends Boolean> arg0, Boolean arg1, Boolean arg2) {
if (arg0 != null && arg2) {
showpopupMenu();
}
}
});
}
/**
* Permet l'affichage du menu popup dans une cellule.
*/
private void showpopupMenu() {
if (!isShowing() && this != null) {
this.show();
}
}
/**
* Ajoute un item à la liste
*
* #param stg String nom de l'item
* #param width double taille préférée
*/
public void addItem(String stg, double width) {
if (stg != null) {
items.add(new BoxItem(stg, items, width));
}
}
/**
* Retourne la description du contenu de la liste
*/
public String toString() {
final StringBuilder stgBuilder = new StringBuilder("[ ");
if (items != null && items.size() > 0) {
final BoxItem lastItem = items.get(items.size() - 1);
for (BoxItem item : items) {
if (item != null) {
stgBuilder.append(item.getName());
if (!item.equals(lastItem)) {
stgBuilder.append(", ");
}
}
}
}
stgBuilder.append(" ]");
return stgBuilder.toString();
}
public class BoxItem extends HBox {
private Label lbl = null;
private Button btn = null;
private ObservableList<BoxItem> listItems;
/**
* Constructeur.
*
* #param stg String nom de la box
* #param items ObservableList<BoxItem> liste d'items de la combobox
* #param prefWidth int largeur de la combobox
*/
public BoxItem(String stg, final ObservableList<BoxItem> items, double prefWidth) {
super();
this.listItems = items;
if (stg != null) {
this.setSpacing(40);
lbl = new Label(stg);
lbl.setPrefWidth(prefWidth);
btn = new Button("x");
this.getChildren().addAll(lbl, btn);
btn.setOnMousePressed(new EventHandler<Event>() {
#Override
public void handle(Event arg0) {
final BoxItem bx = (BoxItem) btn.getParent();
if (bx != null) {
listItems.remove(bx);
}
}
});
}
}
/**
* Retourne le texte inscrit dans le label
*
* #return String
*/
public String getName() {
if (lbl != null) {
return lbl.getText();
}
return null;
}
/**
* retourne le bouton contenu dans une box
*
* #return Button
*/
public Button getBtn() {
return btn;
}
}
}
then I initilise my colum like this with this callbak :
Callback<TableColumn<DonorData, ObservableList<BoxItem>>, TableCell<DonorData, ObservableList<BoxItem>>> cellFactoryEditingCell = new Callback<TableColumn<DonorData, ObservableList<BoxItem>>, TableCell<DonorData, ObservableList<BoxItem>>>() {
public TableCell<DonorData, ObservableList<BoxItem>> call(TableColumn<DonorData, ObservableList<BoxItem>> data) {
return new CbbxEditingCell<DonorData, ObservableList<BoxItem>>();
}
};
colDonorOtherRef.setCellValueFactory(new PropertyValueFactory<DonorData, ObservableList<BoxItem>>("othersRef"));
colDonorOtherRef.setCellFactory(cellFactoryEditingCell);
colDonorOtherRef.setOnEditCommit(new EventHandler<CellEditEvent<DonorData, ObservableList<BoxItem>>>() {
#Override
public void handle(CellEditEvent<DonorData, ObservableList<BoxItem>> event) {
final DonorData rec = event.getTableView().getItems().get(event.getTablePosition().getRow());
//TODO action
}
});
with : CbbxEditingCell.java
public class CbbxEditingCell<S, T> extends TableCell<S, T> {
private CbbxEditSuppr cbbx;
private ObservableList<String> listValues = null;
private boolean isSelectFirst = false;
public CbbxEditingCell() {
listValues = FXCollections.observableArrayList(new ArrayList());
}
#Override
public void startEdit() {
if (!isEmpty()) {
super.startEdit();
createTextField();
setText(null);
setGraphic(cbbx);
}
}
#Override
public void cancelEdit() {
super.cancelEdit();
try {
if (!getItem().toString().equals("null")) {
setText(cbbx.toString());
}
} catch (Exception e) {
}
setGraphic(null);
}
#Override
public void updateItem(T item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setText(null);
setGraphic(null);
} else {
if (isEditing()) {
setText(null);
setGraphic(cbbx);
} else {
if (getItem() != null && cbbx != null) {
setText(cbbx.toString());
} else {
setText(null);
}
setGraphic(null);
}
}
}
private void createTextField() {
final double width = this.getWidth() - this.getGraphicTextGap() * 2;
cbbx = new CbbxEditSuppr((ObservableList<String>) listValues, width);
if (isSelectFirst) {
cbbx.getSelectionModel().selectFirst();
}
cbbx.setMinWidth(width);
cbbx.setOnKeyReleased(new EventHandler<KeyEvent>() {
#Override
public void handle(KeyEvent t) {
if (t.getCode() == KeyCode.ENTER) {
commitEdit((T) cbbx.getItems());
} else if (t.getCode() == KeyCode.ESCAPE) {
cancelEdit();
}
}
});
cbbx.focusedProperty().addListener(new ChangeListener<Boolean>() {
#Override
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
if (!newValue) {
commitEdit((T) cbbx.getItems());
}
}
});
}
public void selectFirstItem() {
isSelectFirst = true;
}
}
My problem : when I click on a cell, I have always an empty combobox. I don't know how modify my callback in order to obtain the reference of the line or of the data represented in this cell.
Do you have any ideas ?
Thanks

I think the problem arises because BoxItem is a Node subclass - i.e. you are mixing view types and data types. (You have BoxItem t; and setGraphic(t); in your updateItem() method.) This is especially bad with a ComboBox, because the selected item ends up trying to appear twice in the scene graph (once in the ComboBox's drop down and once in the "button cell" displaying what's selected).
See "A warning about inserting Nodes into the ComboBox items list" in the ComboBox Javadocs.
Instead, use different classes to represent the data you are displaying and the UI controls to display them.

Related

RecyclerView: how do I bind CheckBox state from ViewHolder to onBindViewHolder?

I have a RecyclerView list of CardViews. Each CardView has a CheckBox that the user can select/de-select. The initial selection launches a Contextual Action Bar. An ArrayList of Integers is used to hold the checkbox state (selected or un-selected). Scrolling and the checkbox views appear to be working correctly. However, when I click a checkbox to de-select it, it remains checked and another checkbox on a different CardView is de-selected? What am I missing here?
Please note that I do not want to set up a ClickListener in onBindViewHolder.
MainActivity.java
public class MainActivity extends AppCompatActivity implements
RecyclerItemClickListener {
private ArrayList<ListItem> allList;
boolean isMultiSelect = false; // for the Contextual Action Bar status
private ActionMode mActionMode;
ArrayList<ListItem> multiselect_list = new ArrayList<>();
private ArrayList<Integer> checkedListItems = new ArrayList<>();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
...
// method from the Adapter, the ItemHolder's onClick()
public void onCheckBoxClick(View view, int position) {
if (!isMultiSelect) {
multiselect_list = new ArrayList<>();
isMultiSelect = true;
if (mActionMode == null) {
mActionMode = startSupportActionMode(actionModeCallback);
}
}
multi_select(position);
}
public void multi_select(int position) {
if (mActionMode != null) {
// If a CardView with a CheckBox already selected is clicked on, then the
// Checkbox is unselected, the position is removed from the multiselect_list
// and the size of the list is decremented by +1.
if (multiselect_list.contains(allList.get(position))) {
multiselect_list.remove(allList.get(position));
}
else {
// If an empty CheckBox on a CardView is clicked on, then the position is added to the
// multiselect_list and the size of the list is incremented by +1.
multiselect_list.add(allList.get(position));
}
if (multiselect_list.size() == 1) {
mActionMode.setTitle("1 selected");
}
else if (multiselect_list.size() >= 2) {
mActionMode.setTitle(multiselect_list.size() + " selected");
}
else if (multiselect_list.size() == 0) {
mActionMode.finish();
}
refreshAdapter();
}
}
public void refreshAdapter() {
adapter.selectedItemsList = multiselect_list;
adapter.mListItems = allList;
adapter.notifyDataSetChanged();
}
private ActionMode.Callback actionModeCallback = new ActionMode.Callback() {
Menu context_menu;
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.menu_action_mode, menu);
context_menu = menu;
return true;
}
...
}
Adapter.java
public class MyRecylerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
public ArrayList<ListItem> mListItems;
private Context mContext;
private RecyclerItemClickListener recyclerItemClickListener;
public ArrayList<ListItem> selectedItemsList = new ArrayList<>();
public MyRecylerAdapter(Context context, ArrayList<ListItem> listItems, ArrayList<ListItem> selectedList) {
this.mContext = context;
this.mListItems = listItems;
this.selectedItemsList = selectedList;
}
private class ItemHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private CheckBox chkSelected;
private ItemHolder(final View itemView) {
super(itemView);
chkSelected = (CheckBox) itemView.findViewById(R.id.chkSelected);
chkSelected.setOnClickListener(this);
}
public void onClick(View v) {
int adapterPos = getAdapterPosition();
// send data to MainActivity() for starting CAB.
if (recyclerItemClickListener !=null) {
recyclerItemClickListener.onCheckBoxClick(v, adapterPos);
}
if (((CheckBox)v).isChecked()) {
checkedListItems.add(adapterPos);
}
else {
checkedListItems.remove(adapterPos);
}
}
void bind(int position) {
if (checkedListItems.contains(position)) {
chkSelected.setChecked(true);
}
else {
chkSelected.setChecked(false);
}
}
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_contact_item, parent, false);
final ItemHolder itemHolder = new ItemHolder(view);
...
return itemHolder;
}
public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
final ListItem listItem = mListItems.get(position);
final ItemHolder itemHolder = (ItemHolder) holder;
itemHolder.bind(position);
...
}
In Adpater declare an ArrayList of integers
ArrayList<Integer> checkedItems = new ArrayList();
And in bind function
void bind(int position) {
if (checkedItems.contains(position)) {
chkSelected.setChecked(true);
}
else {
chkSelected.setChecked(false);
}
}
In OnBindviewholder add below code
CompoundButton.OnCheckedChangeListener onCheckedChangeListener = new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int adapterPos = getAdapterPosition();
if(isChecked) {
checkedItems.add(Integer.valueOf(adapterPos));
}else {
checkedItems.remove(Integer.valueOf(adapterPos));
}
}
}

Migration JBoss AS 7.1.1 to WildFly 8.2

I'm trying to migrate JBoss AS7 to WildFly 8.2 using Hibernate 4.3.7, PostgreSQL, JPA 2.1, JSF 2.2 and Primefaces. I'm connecting to my application normally. When I access page and try to persist data nothing happens, only loads the page and no error occurs.
package br.com.fio.sigaac.backing;
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import br.com.fio.sigaac.dao.AbstractDAO;
import br.com.fio.sigaac.dao.CursoDAO;
import br.com.fio.sigaac.dao.EventoDAO;
import br.com.fio.sigaac.dao.ProcEncerramentoDAO;
import br.com.fio.sigaac.dao.SituacaoFinalMatricDAO;
import br.com.fio.sigaac.to.Evento;
import br.com.fio.sigaac.to.FreqPtcLista;
import br.com.fio.sigaac.to.InstituicaoEnsino;
import br.com.fio.sigaac.to.ParticipanteEvento;
import br.com.fio.sigaac.to.TurmaComplEvento;
import br.com.fio.sigaac.to.TurmaEvento;
import br.com.fio.sigaac.util.JSFUtil;
#ManagedBean
#ViewScoped
public class ProcessaEncEventoBacking {
private List<Evento> listaEventos;
private List<Evento> listaEventoFiltrado;
private List<TurmaEvento> listaTurmaEvento;
private List<TurmaComplEvento> listaSubTurma;
private List<InstituicaoEnsino> listaInstituicao;
private List<InstituicaoEnsino> listaInstituicaoFiltro;
private List<ParticipanteEvento> listaParticipanteMatriculado;
private List<ParticipanteEvento> listaPartMatricFiltrado;
private List<ParticipanteEvento> listaPalestrantes;
private List<FreqPtcLista> listaMovimentacaoParticipante;
private List<ParticipanteEvento> listaInscAgrupada;
private Evento evSalvar = new Evento();
private TurmaEvento turmaSalvar = new TurmaEvento();
private ParticipanteEvento partSelecionado = new ParticipanteEvento();
private InstituicaoEnsino ieSelecionada = new InstituicaoEnsino();
private FreqPtcLista freqPtc = new FreqPtcLista();
EventoDAO evDAO = new EventoDAO();
AbstractDAO abDAO = new AbstractDAO();
SituacaoFinalMatricDAO sDAO = new SituacaoFinalMatricDAO();
ProcEncerramentoDAO pDAO = new ProcEncerramentoDAO();
CursoDAO cursoDAO = new CursoDAO();
private Integer codEvento;
private Integer codTurmaEvento;
private Integer codIes = 9964;
public ProcessaEncEventoBacking() {
criaListaIes();
carregaIES();
}
public void processarEncerramento() {
if (validarProcessamento()) {
this.listaSubTurma = new ArrayList<TurmaComplEvento>(
evDAO.buscaTurmaCompl(codTurmaEvento));
if (listaSubTurma.size() > 0) {
for (int i = 0; i < listaSubTurma.size(); i++) {
pDAO.processarEncerramentoEvento(listaSubTurma.get(i)
.getSubTurma().getId());
}
}
pDAO.processarEncerramentoEvento(turmaSalvar.getId());
selecionaTurmaPorCodigo();
criaListaParticipantesMatriculados(this.turmaSalvar.getId());
JSFUtil.addInfoMessage("Operação realizada com sucesso.");
}
}
public Boolean validarProcessamento() {
if (this.turmaSalvar.getId() < 1) {
JSFUtil.addWarnMessage("Operação não efetuada. Selecione a turma do evento.");
return false;
}
if (this.turmaSalvar.getControlaFreq() == null) {
JSFUtil.addWarnMessage("Operação não efetuada. Verifique os parâmetros da turma do evento.");
return false;
}
if (turmaSalvar.getStatus().getId() == 6) {
JSFUtil.addWarnMessage("Operação não efetuada. O processamento de encerramento já foi realizado e não pode ser alterado.");
return false;
}
System.out.println("Status Turma: " + turmaSalvar.getStatus().getId());
return true;
}
public void carregaIES() {
try {
if ((this.codIes != null) && (this.codIes > 0)) {
this.ieSelecionada = this.cursoDAO
.buscaIESPorCodigo(this.codIes);
if (this.ieSelecionada != null) {
criaListaEventos();
} else {
setCodIes(null);
setIeSelecionada(new InstituicaoEnsino());
JSFUtil.addWarnMessage("Nenhum registro encontrado para o código informado.");
}
} else {
JSFUtil.addWarnMessage("O código informado é inválido.");
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void selecionaIes() {
try {
setCodIes(this.ieSelecionada.getId());
criaListaEventos();
} catch (Exception e) {
e.printStackTrace();
JSFUtil.addErrorMessage("Erro ao selecionar IES. " + e.getMessage());
}
}
public void selecionaEventoPorCodigo() {
if (codIes == null) {
JSFUtil.addWarnMessage("Informe o código da IES");
} else if (codEvento == null) {
JSFUtil.addWarnMessage("Informe o código do evento.");
} else {
setEvSalvar(evDAO.buscarEventoParaEncPorCodigo(codIes, codEvento));
if (evSalvar == null) {
evSalvar = new Evento();
JSFUtil.addWarnMessage("Nenhum registro encontrado para o ID informado.");
} else {
criaListaTurmaPorEvento(evSalvar.getId());
}
}
}
public void selecionaTurmaPorCodigo() {
if (codIes == null) {
JSFUtil.addWarnMessage("Informe o ID da instituição.");
} else if (codTurmaEvento == null) {
JSFUtil.addWarnMessage("Informe o ID da turma.");
} else {
setTurmaSalvar(evDAO.buscaTurmaEvePorCodigo(codEvento,
codTurmaEvento));
if (turmaSalvar == null) {
turmaSalvar = new TurmaEvento();
JSFUtil.addWarnMessage("Nenhum registro encontrado para o ID informado.");
} else {
criaListaParticipantesMatriculados(turmaSalvar.getId());
criaListaPalestrante(turmaSalvar.getId());
}
}
}
public void selecionarEvento() {
setCodEvento(evSalvar.getId());
criaListaTurmaPorEvento(evSalvar.getId());
}
public void selecionarTurmaEvento() {
setCodTurmaEvento(turmaSalvar.getId());
criaListaParticipantesMatriculados(turmaSalvar.getId());
criaListaPalestrante(turmaSalvar.getId());
}
public void criaListaIes() {
this.listaInstituicao = new ArrayList<InstituicaoEnsino>(
this.cursoDAO.listaInstituicao());
}
public void criaListaTurmaPorEvento(Integer idEvento) {
this.listaTurmaEvento = new ArrayList<TurmaEvento>(
evDAO.buscaTurmaPorEvento(idEvento));
}
public void criaListaPalestrante(Integer idTurmaEvento) {
this.listaPalestrantes = new ArrayList<ParticipanteEvento>(
evDAO.listaPalestrantePorTurma(idTurmaEvento));
}
public void criaListaParticipantesMatriculados(Integer idTurmaEvento) {
this.listaParticipanteMatriculado = new ArrayList<ParticipanteEvento>(
evDAO.listaParticipanteMatriculadosPorEvento(idTurmaEvento));
}
public void criaListaEventos() {
this.listaEventos = new ArrayList<Evento>(
evDAO.buscarTodosEventosParaEnc(codIes));
}
public void criaListaMovimentacaoParticipante() {
this.listaMovimentacaoParticipante = new ArrayList<FreqPtcLista>(
pDAO.buscaMovimentacaoParticipante(
this.partSelecionado.getId(), this.turmaSalvar.getId()));
System.out.println("Total: "
+ this.listaMovimentacaoParticipante.size());
}
public List<Evento> getListaEventos() {
return this.listaEventos;
}
public void setListaEventos(List<Evento> listaEventos) {
this.listaEventos = listaEventos;
}
public List<Evento> getListaEventoFiltrado() {
return this.listaEventoFiltrado;
}
public void setListaEventoFiltrado(List<Evento> listaEventoFiltrado) {
this.listaEventoFiltrado = listaEventoFiltrado;
}
public List<TurmaEvento> getListaTurmaEvento() {
return this.listaTurmaEvento;
}
public void setListaTurmaEvento(List<TurmaEvento> listaTurmaEvento) {
this.listaTurmaEvento = listaTurmaEvento;
}
public List<ParticipanteEvento> getListaParticipanteMatriculado() {
return this.listaParticipanteMatriculado;
}
public void setListaParticipanteMatriculado(
List<ParticipanteEvento> listaParticipanteMatriculado) {
this.listaParticipanteMatriculado = listaParticipanteMatriculado;
}
public Evento getEvSalvar() {
return this.evSalvar;
}
public void setEvSalvar(Evento evSalvar) {
this.evSalvar = evSalvar;
}
public TurmaEvento getTurmaSalvar() {
return this.turmaSalvar;
}
public void setTurmaSalvar(TurmaEvento turmaSalvar) {
this.turmaSalvar = turmaSalvar;
}
public List<ParticipanteEvento> getListaPalestrantes() {
return this.listaPalestrantes;
}
public void setListaPalestrantes(List<ParticipanteEvento> listaPalestrantes) {
this.listaPalestrantes = listaPalestrantes;
}
public List<FreqPtcLista> getListaMovimentacaoParticipante() {
return this.listaMovimentacaoParticipante;
}
public void setListaMovimentacaoParticipante(
List<FreqPtcLista> listaMovimentacaoParticipante) {
this.listaMovimentacaoParticipante = listaMovimentacaoParticipante;
}
public ParticipanteEvento getPartSelecionado() {
return this.partSelecionado;
}
public void setPartSelecionado(ParticipanteEvento partSelecionado) {
this.partSelecionado = partSelecionado;
}
public List<ParticipanteEvento> getListaPartMatricFiltrado() {
return this.listaPartMatricFiltrado;
}
public void setListaPartMatricFiltrado(
List<ParticipanteEvento> listaPartMatricFiltrado) {
this.listaPartMatricFiltrado = listaPartMatricFiltrado;
}
public List<ParticipanteEvento> getListaInscAgrupada() {
return this.listaInscAgrupada;
}
public void setListaInscAgrupada(List<ParticipanteEvento> listaInscAgrupada) {
this.listaInscAgrupada = listaInscAgrupada;
}
public InstituicaoEnsino getIeSelecionada() {
return ieSelecionada;
}
public void setIeSelecionada(InstituicaoEnsino ieSelecionada) {
this.ieSelecionada = ieSelecionada;
}
public Integer getCodEvento() {
return codEvento;
}
public void setCodEvento(Integer codEvento) {
this.codEvento = codEvento;
}
public Integer getCodTurmaEvento() {
return codTurmaEvento;
}
public void setCodTurmaEvento(Integer codTurmaEvento) {
this.codTurmaEvento = codTurmaEvento;
}
public Integer getCodIes() {
return codIes;
}
public void setCodIes(Integer codIes) {
this.codIes = codIes;
}
public List<InstituicaoEnsino> getListaInstituicao() {
return listaInstituicao;
}
public void setListaInstituicao(List<InstituicaoEnsino> listaInstituicao) {
this.listaInstituicao = listaInstituicao;
}
public List<InstituicaoEnsino> getListaInstituicaoFiltro() {
return listaInstituicaoFiltro;
}
public void setListaInstituicaoFiltro(
List<InstituicaoEnsino> listaInstituicaoFiltro) {
this.listaInstituicaoFiltro = listaInstituicaoFiltro;
}
public FreqPtcLista getFreqPtc() {
return freqPtc;
}
public void setFreqPtc(FreqPtcLista freqPtc) {
this.freqPtc = freqPtc;
}
public List<TurmaComplEvento> getListaSubTurma() {
return listaSubTurma;
}
public void setListaSubTurma(List<TurmaComplEvento> listaSubTurma) {
this.listaSubTurma = listaSubTurma;
}
}
What am I doing wrong?
Regards.
Renan.

Conversion error in a property in PropertyGrid

I programmed a C# Winforms application. One of the forms allow to configure something, by mean of a PropertyGrid control. I have programmed TypeConverters for a property that is an object that works perfectly, but a little detail.
The property shows a stardard value collection, whose elements are of type Simbologia. The target property is of type CodigoBarra.
The process is as follows: when the first element in the values collection is selected, the property assigns null and no object properties are displayed. When a different value is selected in the collection, the CodigoBarra properties expand, allowing to change the object properties individually.
As I told, all that process work, however, the problem occurs when I set the collection as exclusive. When I press a key, the system is not able to convert from Simbologia to CodigoBarra.
I have tried with ConvertFrom methods, and even, I added an implicit cast to Simbologia class, but it did not help.
The object I am configuring with the Propertygrid is called Equipo, and this is the definition:
public class Equipo : IConfiguracion
{
[Category("Impresora"),
DefaultValue(null),
PropertyOrder(16),
TypeConverter(typeof(PropertyGrid.BarCodeConverter)),
DisplayName("Código de Barras"),
Description("Definición del código de barra cuando se imprime el ticket. El código aparecerá a continuación del texto.")]
public CodigoBarra CodigoBarra { get; set; }
public Equipo()
{
this.NombreBiometrico = this.NombreImpresora = String.Empty;
this.PuertoBiometrico = 4370;
this.IpImpresora = "0.0.0.0";
this.PuertoImpresora = 0;
this.AutoCorte = true;
this.ImprimeTicket = true;
}
public Equipo(string ipBiometrico)
: this()
{
this.ID = 0;
this.IpBiometrico = ipBiometrico;
this.Nuevo = true;
}
public Equipo(string nombreBiometrico, string ipBiometrico)
: this()
{
this.ID = 0;
this.NombreBiometrico = nombreBiometrico;
this.IpBiometrico = ipBiometrico;
this.Nuevo = true;
}
public Equipo(int id, string ipBiometrico)
: this()
{
this.ID = id;
this.IpBiometrico = ipBiometrico;
this.Nuevo = id == 0;
}
public Equipo(int id, string nombreBiometrico, string ipBiometrico)
: this()
{
this.ID = id;
this.NombreBiometrico = nombreBiometrico;
this.IpBiometrico = ipBiometrico;
this.Nuevo = id == 0;
}
}
I have left only CodigoBarra property.
BarCodeConverter is as follows:
public class BarCodeConverter : TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
return sourceType == typeof(string) || sourceType == typeof(MonitorView.Configuracion.Simbologia) || base.CanConvertFrom(context, sourceType);
}
public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
{
string stringValue = value as string;
object result = null;
if (!string.IsNullOrEmpty(stringValue))
{
var valor = new Configuracion.Simbologia(stringValue);
if (valor.Codigo != InDriver.BarCodeInfo.SymbologyDef.None)
result = new MonitorView.Configuracion.CodigoBarra(valor);
}
return result;
}
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
{
MonitorView.Configuracion.CodigoBarra codigoBarra = value as MonitorView.Configuracion.CodigoBarra;
object result = null;
if (codigoBarra == null)
{
if (value != null)
{
Configuracion.Simbologia simbologia = value as Configuracion.Simbologia;
if (destinationType == typeof(string) && !Configuracion.Simbologia.IsNone(simbologia))
result = simbologia.ToString();
}
}
else
{
if (destinationType == typeof(string) && !Configuracion.Simbologia.IsNone(codigoBarra.Symbology))
result = codigoBarra.ToString();
}
if (String.IsNullOrEmpty((string)result))
result = "[ ninguno ]";
return result ?? base.ConvertTo(context, culture, value, destinationType);
}
public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
{
return true;
}
public override bool GetStandardValuesExclusive(ITypeDescriptorContext context)
{
return true;
}
public override TypeConverter.StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
{
return new StandardValuesCollection(Configuracion.Simbologia.GetValues());
}
public override bool GetPropertiesSupported(ITypeDescriptorContext context)
{
return true;
}
public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, Attribute[] attributes)
{
return TypeDescriptor.GetProperties(value, attributes);
}
}
As you see in GetStandardValues method, the collection is built with Configuracion.Simbologia.GetValues() call, which returns an array of Simbologia objects.
It is obvious that the mismatch will be produced but, why the error is produced only when I press a key? When I select the Simbologia object using the dropdownlist, it works.
Finally, this is the implicit cast I implemented in Simbologia class:
public static implicit operator CodigoBarra(Simbologia simbologia)
{
return new CodigoBarra(simbologia);
}
How can I solve it?
Any help will be greatly appreciated.
Thanks
Jaime
Finally, I have solved it using this type converter:
public class BarCodeConverter : TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
return sourceType == typeof(string) || sourceType == typeof(MonitorView.Configuracion.Simbologia) || base.CanConvertFrom(context, sourceType);
}
public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
{
string stringValue = value as string;
object result = null;
if (!string.IsNullOrEmpty(stringValue))
{
var valor = new Configuracion.Simbologia(stringValue);
if (valor.Codigo != InDriver.BarCodeInfo.SymbologyDef.None)
result = new MonitorView.Configuracion.CodigoBarra(valor);
}
return result;
}
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
{
MonitorView.Configuracion.CodigoBarra codigoBarra = value as MonitorView.Configuracion.CodigoBarra;
object result = null;
if (codigoBarra == null)
{
if (value != null)
{
Configuracion.Simbologia simbologia = value as Configuracion.Simbologia;
if (destinationType == typeof(string) && !Configuracion.Simbologia.IsNone(simbologia))
result = simbologia.ToString();
}
}
else
{
if (destinationType == typeof(string) && !Configuracion.Simbologia.IsNone(codigoBarra.Symbology))
result = codigoBarra.ToString();
}
if (String.IsNullOrEmpty((string)result))
result = "[ ninguno ]";
return result ?? base.ConvertTo(context, culture, value, destinationType);
}
public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
{
return true;
}
public override bool GetStandardValuesExclusive(ITypeDescriptorContext context)
{
return true;
}
public override TypeConverter.StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
{
return new StandardValuesCollection(Configuracion.Simbologia.GetValues());
}
public override bool GetPropertiesSupported(ITypeDescriptorContext context)
{
return true;
}
public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, Attribute[] attributes)
{
return TypeDescriptor.GetProperties(value, attributes);
}
}
This is Symbologia class:
public class Simbologia
{
public InDriver.BarCodeInfo.SymbologyDef Codigo { get; set; }
public Simbologia(InDriver.BarCodeInfo.SymbologyDef codigo)
{
this.Codigo = codigo;
}
public Simbologia(string nombreCodigo)
{
this.Codigo = Enum.GetValues(typeof(InDriver.BarCodeInfo.SymbologyDef)).Cast<InDriver.BarCodeInfo.SymbologyDef>().Where(s => s.ToString() == nombreCodigo).FirstOrDefault();
}
public static implicit operator CodigoBarra(Simbologia simbologia)
{
return new CodigoBarra(simbologia);
}
public override string ToString()
{
return this.Codigo.ToString();
}
public static Array GetValues(params object[] excludes)
{
var valores = Enum.GetValues(typeof(InDriver.BarCodeInfo.SymbologyDef)).Cast<InDriver.BarCodeInfo.SymbologyDef>();
List<Simbologia> simbologias = new List<Simbologia>(valores.Count());
foreach (var valor in valores)
if (excludes.Count() == 0 || excludes.FirstOrDefault(e => e.ToString() == valor.ToString()) == null)
simbologias.Add(new Simbologia(valor));
return simbologias.ToArray();
}
public static bool IsNone(Simbologia simbologia)
{
return simbologia == null || simbologia.Codigo == InDriver.BarCodeInfo.SymbologyDef.None;
}
And finally, this is CodigoBarra class:
[TypeConverter(typeof(PropertySorter))]
public class CodigoBarra
{
[DefaultValue(70),
PropertyOrder(1),
TypeConverter(typeof(StringConverter)),
DisplayName("Alto"),
Description("Alto del código de barras, en puntos (depende de la impresora).")]
public byte Height { get; set; }
[DefaultValue(2),
PropertyOrder(2),
TypeConverter(typeof(StringConverter)),
DisplayName("Ancho"),
Description("Ancho del código de barras, en puntos (depende de la impresora).")]
public byte Width { get; set; }
[DefaultValue(0),
PropertyOrder(3),
TypeConverter(typeof(StringConverter)),
DisplayName("Alineamiento"),
Description("Distancia desde el borde izquierdo del código de barras, en puntos (depende de la impresora).")]
public byte Alignment { get; set; }
[DefaultValue(InDriver.BarCodeInfo.TextPositionDef.None),
PropertyOrder(4),
DisplayName("Posición del Texto"),
Description("Posición del texto con respecto al código de barras.")]
public InDriver.BarCodeInfo.TextPositionDef TextPosition { get; set; }
[DefaultValue(null),
PropertyOrder(5),
DisplayName("Simbología"),
TypeConverter(typeof(PropertyGrid.SymbologyConverter)),
Description("Tipo de simbología con la cual se codifica el código de barra. No todas las impresoras soportan las mismas simbologías.")]
public Simbologia Symbology { get; set; }
public CodigoBarra()
{
this.Symbology = null;
this.Alignment = 0;
this.Height = 70;
this.Width = 2;
this.TextPosition = InDriver.BarCodeInfo.TextPositionDef.None;
}
public CodigoBarra(Simbologia symbology, byte alignment, byte height, byte width, InDriver.BarCodeInfo.TextPositionDef textPosition)
{
this.Symbology = symbology;
this.Alignment = alignment;
this.Height = height;
this.Width = width;
this.TextPosition = textPosition;
}
public CodigoBarra(Simbologia symbology)
: this()
{
this.Symbology = symbology;
}
public CodigoBarra(InDriver.BarCodeInfo info)
: this()
{
SetBarCodeInfo(info);
}
public CodigoBarra(string info)
: this()
{
SetBarCodeInfo(InDriver.BarCodeInfo.GetInformation(info));
}
public InDriver.BarCodeInfo GetBarCodeInfo()
{
InDriver.BarCodeInfo info = new InDriver.BarCodeInfo();
info.Symbology = this.Symbology == null ? InDriver.BarCodeInfo.SymbologyDef.None : this.Symbology.Codigo;
info.Height = this.Height;
info.Width = this.Width;
info.Alignment = this.Alignment;
info.TextPosition = this.TextPosition;
return info;
}
public void SetBarCodeInfo(InDriver.BarCodeInfo info)
{
if (info != null)
{
this.Symbology = new Simbologia(info.Symbology);
this.Height = info.Height;
this.Width = info.Width;
this.Alignment = info.Alignment;
this.TextPosition = info.TextPosition;
}
}
public override string ToString()
{
return this.Symbology.ToString();
}
}
Regards,
Jaime

JavaFX ComboBox setButtonCell

i need help about settings the combobox buttonCell.
I use a combobox that show data from an observable list that contains data from a table with two columns, "Step" and "NextStep" (NextStep contains one item inserted in column Step); what i need to do is to show the combobox listcell with the list of "Step" and the buttoncell with the relative "NextStep". Now, i can see the listcell correctly but my buttoncell is always empty.
The code:
// SET THE VALUE STEP TO THE LISTCELL
comboStatoSuccessivo.setCellFactory(new Callback<ListView<StatoEsiti>, ListCell<StatoEsiti>>() {
#Override public ListCell<StatoEsiti> call(ListView<StatoEsiti> p) {
return new ListCell<StatoEsiti>() {
#Override
protected void updateItem(StatoEsiti t, boolean bln) {
super.updateItem(t, bln);
if(t != null){
setText(t.statoProperty().getValue());
System.out.println("SET PROPERTY " + t.statoProperty().getValue());
} else {
setText(null);
}
}
};
}
});
// SET THE VALUE NEXTSTEP TO THE BUTTONCELL
comboStatoSuccessivo.setButtonCell(new ListCell<StatoEsiti>() {
#Override
protected void updateItem(StatoEsiti t, boolean bln) {
super.updateItem(t, bln);
if (t != null) { <<<<<<<<<<<<<<-------------ALWAYS NULL----WHY??????
setText(t.statoSuccessivoProperty().getValue());
System.out.println("SET PROPERTY BUTTONCELL " + t.statoSuccessivoProperty().getValue());
} else {
setText(null);
System.out.println("SET PROPERTY BUTTONCELL NULL");
}
}
});
Thanks in advance.
I have looked into your use case with the following demo SSCCE code.
It is working as expected, like as when the item is selected from the combobox's dropmenu the buttoncell is updated with related "nextStep":
public class ComboDemo extends Application {
#Override
public void start(Stage primaryStage) {
List<Person> list = new ArrayList<Person>();
list.add(new Person("step 1212", 12));
list.add(new Person("step 4545", 45));
list.add(new Person("step 5656", 56));
list.add(new Person("step 9090", 90));
ComboBox<Person> comboBox = new ComboBox<>(FXCollections.observableList(list));
comboBox.setCellFactory(new Callback<ListView<Person>, ListCell<Person>>() {
#Override
public ListCell<Person> call(ListView<Person> p) {
return new ListCell<Person>() {
#Override
protected void updateItem(Person t, boolean bln) {
super.updateItem(t, bln);
if (t != null) {
setText(t.getStepProperty().getValue());
System.out.println("SET PROPERTY " + t.getStepProperty().getValue());
} else {
setText(null);
}
}
};
}
});
// SET THE VALUE NEXTSTEP TO THE BUTTONCELL
comboBox.setButtonCell(new ListCell<Person>() {
#Override
protected void updateItem(Person t, boolean bln) {
super.updateItem(t, bln);
if (t != null) {
setText(t.getNextStepProperty().getValue().toString());
System.out.println("SET PROPERTY BUTTONCELL " + t.getNextStepProperty().getValue());
} else {
setText(null);
System.out.println("SET PROPERTY BUTTONCELL NULL");
}
}
});
StackPane root = new StackPane();
root.getChildren().add(comboBox);
Scene scene = new Scene(root, 300, 250);
primaryStage.setScene(scene);
primaryStage.show();
}
public static class Person {
private StringProperty stepProperty = new SimpleStringProperty();
private IntegerProperty nextStepProperty = new SimpleIntegerProperty();
public Person(String step, Integer nextStep) {
this.stepProperty.setValue(step);
this.nextStepProperty.setValue(nextStep);
}
public StringProperty getStepProperty() {
return stepProperty;
}
public void setStepProperty(StringProperty stepProperty) {
this.stepProperty = stepProperty;
}
public IntegerProperty getNextStepProperty() {
return nextStepProperty;
}
public void setNextStepProperty(IntegerProperty nextStepProperty) {
this.nextStepProperty = nextStepProperty;
}
}
public static void main(String[] args) {
launch(args);
}
}
Compare it with yours.

How to display different value with ComboBoxTableCell?

I try to use ComboxBoxTableCell without success.
The content of the cell display the right value for the attribute of an object. But when the combobox is displayed, all items are displayed with the toString object method and not the attribute.
I tryed to override updateItem of ComboBoxTableCell or to provide a StringConverter but nothing works.
Do you have some ideas to custom comboxbox list display in a table cell ?
I put a short example below to see quickly the problem. Execute the app and click in the cell, you will see the combobox with toString value of the object.
package javafx2;
import javafx.application.Application;
import javafx.beans.property.adapter.JavaBeanObjectPropertyBuilder;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableColumn.CellDataFeatures;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.ComboBoxTableCell;
import javafx.stage.Stage;
import javafx.util.Callback;
import javafx.util.StringConverter;
public class ComboBoxTableCellTest extends Application {
public class Product {
private String name;
public Product(String name) {
this.name = name;
}
public String getName() { return name; }
public void setName(String name) { this.name = name; }
}
public class Command {
private Integer quantite;
private Product product;
public Command(Product product, Integer quantite) {
this.product = product;
this.quantite = quantite;
}
public Integer getQuantite() { return quantite; }
public void setQuantite(Integer quantite) { this.quantite = quantite; }
public Product getProduct() { return product; }
public void setProduct(Product product) { this.product = product; }
}
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage stage) throws Exception {
Product p1 = new Product("Product 1");
Product p2 = new Product("Product 2");
final ObservableList<Product> products = FXCollections.observableArrayList(p1, p2);
ObservableList<Command> commands = FXCollections.observableArrayList(new Command(p1, 20));
TableView<Command> tv = new TableView<Command>();
tv.setItems(commands);
TableColumn<Command, Product> tc = new TableColumn<Command, Product>("Product");
tc.setMinWidth(140);
tc.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<Command,Product>, ObservableValue<Product>>() {
#Override
public ObservableValue<Product> call(CellDataFeatures<Command, Product> cdf) {
try {
JavaBeanObjectPropertyBuilder<Product> jbdpb = JavaBeanObjectPropertyBuilder.create();
jbdpb.bean(cdf.getValue());
jbdpb.name("product");
return (ObservableValue) jbdpb.build();
} catch (NoSuchMethodException e) {
System.err.println(e.getMessage());
}
return null;
}
});
final StringConverter<Product> converter = new StringConverter<ComboBoxTableCellTest.Product>() {
#Override
public String toString(Product p) {
return p.getName();
}
#Override
public Product fromString(String s) {
// TODO Auto-generated method stub
return null;
}
};
tc.setCellFactory(new Callback<TableColumn<Command,Product>, TableCell<Command,Product>>() {
#Override
public TableCell<Command, Product> call(TableColumn<Command, Product> tc) {
return new ComboBoxTableCell<Command, Product>(converter, products) {
#Override
public void updateItem(Product product, boolean empty) {
super.updateItem(product, empty);
if (product != null) {
setText(product.getName());
}
}
};
}
});
tv.getColumns().add(tc);
tv.setEditable(true);
Scene scene = new Scene(tv, 140, 200);
stage.setScene(scene);
stage.show();
}
}
Desculpe-me Philippe Jean por respondê-lo em português, mas como não domino bem sua língua, achei melhor desta forma.
Encontrei o mesmo problema que o seu e solucionei-o com a seguinte implementação.
I found the same problem as yours and solved it with the following implementation.
final ObservableList<Product> products = FXCollections.observableArrayList(p1, p2);
ObservableList<Command> commands = FXCollections.observableArrayList(new Command(p1, 20));
TableView<Command> tv = new TableView<Command>();
tv.setItems(commands);
/**
* Substitua as sugestões de tipo Product por String da TableColumn e suas correlacionadas como abaixo
*/
TableColumn<Command, String> tc = new TableColumn<Command, String>("Product");
tc.setMinWidth(140);
tc.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<Command, String>, ObservableValue<String>>(){
#Override
public ObservableValue<String> call(CellDataFeatures<Command, String> p) {
return new SimpleObjectProperty(p.getValue().getProduct().getName());
}
});
tc.setCellFactory(new Callback<TableColumn<Command, String>, TableCell<Command, String>>() {
#Override
public TableCell<Command, String> call(TableColumn<Command, String> p) {
/**
* Este Map guardará os objetos Product indexando pelo "name"
*/
final Map<String, Product> products = new HashMap();
Iterator<Product> productsi = pojosComboBox.iterator();
while(productsi.hasNext()) {
Product product = productsi.next();
products.put(product.getName(), product);
}
ComboBoxTableCell cell = new ComboBoxTableCell(FXCollections.observableArrayList(products.keySet())){
#Override
public void updateItem(Object item, boolean empty) {
super.updateItem(item, empty);
if(item != null) {
/**
* Aqui acontece a atualização do objeto Command de acordo com o esperado
*/
tabela.getItems().get(getIndex()).setProduct(products.get(item.toString()));
}
}
};
cell.setAlignment(Pos.CENTER);
return cell;
}
});

Resources