Migration JBoss AS 7.1.1 to WildFly 8.2 - database

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.

Related

Prism INavigationAware Interface not invoking IsNavigationTarget

I am using prism 6 and on my application I have modules. I want to navigate to different views on different modules and I am using INavigationAware Interface. I can call OnNavigatedFrom every time I am navigating away from current view but when I enter a new view OnNavigatedTo is not fired which is giving me a headache. I will post my code from bootstrap to viewmodel for one module.
Bootstraper.cs
public class Bootstrapper : UnityBootstrapper
{
#region Members
private ILog _logger;
#endregion
#region Properties
#endregion
#region Methods
protected override DependencyObject CreateShell()
{
_logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
RegisterTypes();
return Container.Resolve<AppShell>();
}
protected override void InitializeShell()
{
App.Current.MainWindow = (Window)this.Shell;
App.Current.MainWindow.Show();
}
protected void RegisterTypes()
{
Container.RegisterType<ILogger, Log4NetLogger>(new InjectionConstructor(_logger));
Container.RegisterType<IEncryption, SymmetricEncryption>();
Container.RegisterType<IGetSavviUow, GetSavviUowMock>();
Container.RegisterType<ICustomAuthentication, MockCustomAuthentication>();
Container.RegisterType<ICustomPrincipal, CustomPrincipal>();
Container.RegisterType<IIdNumberValidation, IdNumberValidation>();
Container.RegisterType<ISalesValidation, SalesValidation>();
AutoMapperConfig.RegisterMappings();
}
protected override void ConfigureModuleCatalog()
{
ModuleCatalog.AddModule(new ModuleInfo()
{
InitializationMode = InitializationMode.WhenAvailable,
ModuleType = typeof(LoginModuleDefinition).AssemblyQualifiedName,
ModuleName = typeof(LoginModuleDefinition).Name
});
ModuleCatalog.AddModule(new ModuleInfo()
{
InitializationMode = InitializationMode.OnDemand,
ModuleType = typeof(AgentQueueModuleDefinition).AssemblyQualifiedName,
ModuleName = typeof(AgentQueueModuleDefinition).Name
});
ModuleCatalog.AddModule(new ModuleInfo()
{
InitializationMode = InitializationMode.OnDemand,
ModuleType = typeof(PreQualificationModuleDefinition).AssemblyQualifiedName,
ModuleName = typeof(PreQualificationModuleDefinition).Name
});
ModuleCatalog.AddModule(new ModuleInfo()
{
InitializationMode = InitializationMode.OnDemand,
ModuleType = typeof(SearchModuleDefinition).AssemblyQualifiedName,
ModuleName = typeof(SearchModuleDefinition).Name
});
ModuleCatalog.AddModule(new ModuleInfo()
{
InitializationMode = InitializationMode.OnDemand,
ModuleType = typeof(PlanSelectionModuleDefinition).AssemblyQualifiedName,
ModuleName = typeof(PlanSelectionModuleDefinition).Name
});
ModuleCatalog.AddModule(new ModuleInfo()
{
InitializationMode = InitializationMode.OnDemand,
ModuleType = typeof(BenefitsScriptModuleDefinition).AssemblyQualifiedName,
ModuleName = typeof(BenefitsScriptModuleDefinition).Name
});
ModuleCatalog.AddModule(new ModuleInfo()
{
InitializationMode = InitializationMode.OnDemand,
ModuleType = typeof(PersonalInfoModuleDefinition).AssemblyQualifiedName,
ModuleName = typeof(PersonalInfoModuleDefinition).Name
});
}
protected override void InitializeModules()
{
base.InitializeModules();
}
#endregion
#region Constructors
#endregion
}
ShellViewModel.cs
public class ShellViewModel : ViewModelBase
{
#region Members
private string _username;
private bool _isLoggedIn;
private string _viewName;
private bool _canCreateNewMembership;
private bool _canUpgrade;
private bool _canReinstate;
private bool _canContinue;
private ILogger _logger;
private IModuleManager _moduleManager;
private IRegionManager _regionManager;
private Guid _agentRefId;
#endregion
#region Properties
public string Username
{
get { return _username; }
set
{
SetProperty(ref _username, value);
}
}
public bool IsLoggedIn
{
get { return _isLoggedIn; }
set { SetProperty(ref _isLoggedIn, value); }
}
public string ViewName
{
get { return _viewName; }
set { SetProperty(ref _viewName, value); }
}
#endregion
#region Methods
private void InitDelegateCommands()
{
this.LogoutCommand = new DelegateCommand(Logout);
this.ContinueCommand = new DelegateCommand<string>(Continue, CanContinue);
this.CreateNewMembershipCommand = new DelegateCommand(CreateNewMembership, CanCreateNewMembership);
this.ExitApplicationCommand = new DelegateCommand(ExitApplication);
this.ReinstateCommand = new DelegateCommand(Reinstate, CanReinstate);
this.SaveAndExitCommand = new DelegateCommand(SaveAndExit);
this.SaveProgressCommand = new DelegateCommand(Save);
this.SetCallBackCommand = new DelegateCommand(SetCallBack);
this.UpgradeCommand = new DelegateCommand(Upgrade, CanUpgrade);
}
private bool CanContinue(string navigatingTo)
{
this.NavigatingToView = navigatingTo;
return _canContinue;
}
private void Continue(string currentView)
{
this.Aggregator.GetEvent<ContinueEvent>().Publish(
this.ViewNavigationList
.First(x =>
x.CurrentView == currentView).RequestedView);
}
private bool CanUpgrade()
{
return _canUpgrade;
}
private void Upgrade()
{
this.Aggregator.GetEvent<UpgradeEvent>().Publish(_agentRefId);
}
private void Logout()
{
ICustomPrincipal customPrincipal = Thread.CurrentPrincipal as ICustomPrincipal;
if (customPrincipal != null)
{
customPrincipal.CustomIdentity = new AnonymousIdentity();
this.Username = string.Empty;
this.IsLoggedIn = false;
ShowView(ModuleViewConstants.LoginView);
}
}
private void SetCallBack()
{
this.Aggregator.GetEvent<SetCallBackEvent>().Publish(_agentRefId);
}
private void Save()
{
this.Aggregator.GetEvent<SaveEvent>().Publish(_agentRefId);
}
private void SaveAndExit()
{
this.Aggregator.GetEvent<SaveEvent>().Publish(_agentRefId);
}
private bool CanReinstate()
{
return _canReinstate;
}
private void Reinstate()
{
this.Aggregator.GetEvent<ContinueEvent>().Publish(ModuleViewConstants.PlanSelectionView);
}
private bool CanCreateNewMembership()
{
return _canCreateNewMembership;
}
private void CreateNewMembership()
{
this.Aggregator.GetEvent<ContinueEvent>().Publish(ModuleViewConstants.PlanSelectionView);
}
private void ExitApplication()
{
this.Aggregator.GetEvent<ExitApplicationEvent>().Publish(_agentRefId);
}
private void OnLoggedOn(LoggedOnArgument args)
{
this.Username = args.Username;
this.IsLoggedIn = args.IsLoggedOn;
_agentRefId = args.AgentRefId;
LoadModules();
_regionManager.Regions[RegionConstants.QueueRegion].Context = _agentRefId;
ShowView(ModuleViewConstants.PreQualificationView);
}
private void LoadModules()
{
_moduleManager.LoadModule(typeof(AgentQueueModuleDefinition).Name);
_moduleManager.LoadModule(typeof(SearchModuleDefinition).Name);
_moduleManager.LoadModule(typeof(PreQualificationModuleDefinition).Name);
_moduleManager.LoadModule(typeof(PlanSelectionModuleDefinition).Name);
_moduleManager.LoadModule(typeof(BenefitsScriptModuleDefinition).Name);
_moduleManager.LoadModule(typeof(PersonalInfoModuleDefinition).Name);
}
private void ShowView(string view)
{
this.ViewName = view;
this.CurrentView = view;
_regionManager.RequestNavigate(
RegionConstants.OperationsRegion,
new Uri(view, UriKind.Relative));
}
private void AssingCanCreateNewMembership(bool canCreateMembership)
{
_canCreateNewMembership = canCreateMembership;
CreateNewMembershipCommand.RaiseCanExecuteChanged();
}
private void AssignCanContinue(bool canContinue)
{
_canContinue = canContinue;
ContinueCommand.RaiseCanExecuteChanged();
}
private void AssignCanUpgrade(bool canUpgrade)
{
_canUpgrade = canUpgrade;
UpgradeCommand.RaiseCanExecuteChanged();
}
private void AssignCanReinstate(bool canReinstate)
{
_canReinstate = canReinstate;
ReinstateCommand.RaiseCanExecuteChanged();
}
private void EventSubscriptions()
{
this.Aggregator.GetEvent<LoggedOnEvent>().Subscribe(OnLoggedOn);
this.Aggregator.GetEvent<ShowViewEvent>().Subscribe(ShowView);
this.Aggregator.GetEvent<CanCreateNewMembership>().Subscribe(AssingCanCreateNewMembership);
this.Aggregator.GetEvent<CanContinueEvent>().Subscribe(AssignCanContinue);
this.Aggregator.GetEvent<CanUpgradeEvent>().Subscribe(AssignCanUpgrade);
this.Aggregator.GetEvent<CanReinstateEvent>().Subscribe(AssignCanReinstate);
}
#endregion
#region Commands
public DelegateCommand LogoutCommand { get; set; }
public DelegateCommand ExitApplicationCommand { get; set; }
public DelegateCommand<string> ContinueCommand { get; set; }
public DelegateCommand SaveProgressCommand { get; set; }
public DelegateCommand SetCallBackCommand { get; set; }
public DelegateCommand SaveAndExitCommand { get; set; }
public DelegateCommand CreateNewMembershipCommand { get; set; }
public DelegateCommand ReinstateCommand { get; set; }
public DelegateCommand UpgradeCommand { get; set; }
#endregion
#region Events
#endregion
#region Construction
public ShellViewModel(
IRegionManager regionManager,
IUnityContainer container,
IEventAggregator aggregator,
IModuleManager moduleManager,
ILogger logger)
: base(aggregator, container)
{
_logger = logger;
_logger.Info("Starting Shell");
_moduleManager = moduleManager;
_regionManager = regionManager;
InitDelegateCommands();
EventSubscriptions();
}
#endregion
}
PreQualificationModule
PreQualificationModuleDefinition.cs
public class PreQualificationModuleDefinition : IModule
{
#region Members
private IRegionManager _regionManager;
private IUnityContainer _container;
#endregion
#region Properties
#endregion
#region Methods
public void Initialize()
{
_container.RegisterType<object, PreQualificationView>(ModuleViewConstants.PreQualificationView);
_regionManager.RegisterViewWithRegion(RegionConstants.OperationsRegion, typeof(PreQualificationView));
}
#endregion
#region Constructors
public PreQualificationModuleDefinition(
IRegionManager regionManager,
IUnityContainer container)
{
_regionManager = regionManager;
_container = container;
}
#endregion
}
PreQualificationViewModel.cs
public class PreQualificationViewModel : ViewModelBase, INavigationAware
{
#region Members
private string _name;
private int _selectedIdType;
private string _contactNumber;
private string _idNumber;
private DateTime? _dateOfBirth;
private int? _age;
private string _gender;
private string _passportNumber;
private bool _isCitizen;
private bool _isSearch;
private bool _showUserControl;
private bool _showPassportFields;
private bool _hasContactNumber;
private ObservableCollection<string> _genderList;
private int? _planId;
private IList<PolicyGrid> _policies;
private Principal _mainMember;
private Lead _lead;
private Membership _membership;
private IGetSavviUow _uow;
private IIdNumberValidation _idNumberValidation;
private ICustomPrincipal _principal;
private ISalesValidation _salesValidation;
private IRegionManager _regionManager;
#endregion
#region Properties
public string Name
{
get { return _name; }
set { SetProperty(ref _name, value); }
}
public int SelectedIdType
{
get { return _selectedIdType; }
set
{
SetProperty(ref _selectedIdType, value, this);
if (_selectedIdType == 2)
{
this.ShowPassportFields = true;
this.IsCitizen = false;
}
else
{
this.ShowPassportFields = false;
this.IsCitizen = true;
}
}
}
public ObservableCollection<KeyValuePair<int, string>> IdTypes
{
get
{
return new ObservableCollection<KeyValuePair<int, string>>()
{
new KeyValuePair<int, string>(1, "RSA ID Number"),
new KeyValuePair<int, string>(2, "Passport")
};
}
}
[Required]
public string ContactNumber
{
get { return _contactNumber; }
set
{
SetProperty(ref _contactNumber, value, this);
}
}
[IdValidation("SelectedIdType")]
[RequiredIf("SelectedIdType", 1)]
[Display(Name = "ID Number")]
public string IdNumber
{
get { return _idNumber; }
set
{
SetProperty(ref _idNumber, value, this);
if (_idNumberValidation.IsCitizen(_idNumber))
{
this.IsCitizen = true;
SetIdProperties();
}
}
}
[RequiredIf("SelectedIdType", 2)]
[Display(Name = "Date of Birth")]
public Nullable<DateTime> DateOfBirth
{
get { return _dateOfBirth; }
set
{
SetProperty(ref _dateOfBirth, value, this);
if (_dateOfBirth != null)
this.Age = DateTime.Today.Year - _dateOfBirth.Value.Year;
}
}
[AgeMinMax("PlanId")]
public Nullable<int> Age
{
get { return _age; }
set
{
SetProperty(ref _age, value, this);
}
}
[RequiredIf("SelectedIdType", 2)]
public string Gender
{
get { return _gender; }
set
{
SetProperty(ref _gender, value, this);
}
}
public ObservableCollection<string> GenderList
{
get { return _genderList; }
set
{
SetProperty(ref _genderList, value);
}
}
[RequiredIf("SelectedIdType", 2)]
[Display(Name = "Passport Number")]
public string PassportNumber
{
get { return _passportNumber; }
set
{
SetProperty(ref _passportNumber, value, this);
}
}
public bool IsCitizen
{
get { return _isCitizen; }
set { SetProperty(ref _isCitizen, value, this); }
}
public bool IsSearch
{
get { return _isSearch; }
set { SetProperty(ref _isSearch, value, this); }
}
public bool ShowUserControl
{
get { return _showUserControl; }
set { SetProperty(ref _showUserControl, value, this); }
}
public bool ShowPassportFields
{
get { return _showPassportFields; }
set { SetProperty(ref _showPassportFields, value, this); }
}
public bool HasContactNumber
{
get { return _hasContactNumber; }
set { SetProperty(ref _hasContactNumber, value, this); }
}
public Nullable<int> PlanId
{
get { return _planId; }
set { _planId = value; }
}
public IList<PolicyGrid> Policies
{
get { return _policies; }
set { SetProperty(ref _policies, value); }
}
#endregion
#region Methods
private void SetIdProperties()
{
this.Age = _idNumberValidation.GetAge(DateTime.Today, this.IdNumber);
this.DateOfBirth = _idNumberValidation.GetDateOfBirth(this.IdNumber);
this.Gender = _idNumberValidation.GetGender(this.IdNumber);
}
private void GetLeadInfo(int callQueueId)
{
ClearProperties();
var callQueue = _uow.RepoCallQueue.GetLeadByCallQueueIdRefId(callQueueId, _principal.CustomIdentity.RefId);
this.ShowUserControl = true;
var leadCallQueue = callQueue.Lead_CallQueue.FirstOrDefault(x => x.CallQueueId == callQueueId);
_lead = leadCallQueue.Lead;
this.Name = _lead.FirstName + " " + _lead.Surname;
this.IdNumber = _lead.IdNumber;
this.PlanId = _lead.PlanId;
if (!string.IsNullOrEmpty(_lead.Mobile))
{
this.HasContactNumber = true;
this.ContactNumber = _lead.Mobile;
}
if (!string.IsNullOrEmpty(_lead.IdNumber) &&
_idNumberValidation.IsCitizen(_lead.IdNumber))
{
this.SelectedIdType = 1;
}
else if (!string.IsNullOrEmpty(_lead.IdNumber))
{
this.SelectedIdType = 2;
}
}
private void ClearProperties()
{
this.IdNumber = string.Empty;
this.DateOfBirth = null;
this.Gender = null;
this.Age = null;
}
private void SearchedMembership(SearchArgs arg)
{
ClearProperties();
this.ShowUserControl = true;
List<Membership> memberships = new List<Membership>();
if (!string.IsNullOrEmpty(arg.SearchedId))
{
switch (arg.SearchingType)
{
case 1:
//Membership Number
memberships = _uow.RepoMembership.GetMembershipsByMembershipNumber(Convert.ToInt32(arg.SearchedId)).ToList();
break;
case 2:
//ID Number
memberships = _uow.RepoMembership.GetMembershipsByIdNumber(arg.SearchedId).ToList();
break;
case 3:
//Passport
memberships = _uow.RepoMembership.GetMembershipsByPassport(arg.SearchedId).ToList();
break;
default:
throw new ArgumentException("Uknown Searching type!");
}
_mainMember = memberships.FirstOrDefault().Principal;
if(memberships.Count > 0)
this.Policies = memberships.Select(x => new PolicyGrid(
x.Id,
_uow.Plan.GetById(x.PlanId.Value).Description,
_uow.MembershipStatus.GetById(x.MembershipStatusId).Description,
x.CommenceDate.HasValue?x.CommenceDate.Value.ToString("dd/MM/yyyy") : null,
x.ResignationDate.HasValue ? x.ResignationDate.Value.ToString("dd/MM/yyyy") : null)).ToList();
this.Name = _mainMember.FirstName + " " + _mainMember.Surname;
this.IdNumber = _mainMember.IdNumber;
this.PlanId = _uow.RepoMembership.GetLatestMembership(this.IdNumber).PlanId;
if (!string.IsNullOrEmpty(_mainMember.Mobile))
{
this.HasContactNumber = true;
this.ContactNumber = _mainMember.Mobile;
}
if (!string.IsNullOrEmpty(_mainMember.IdNumber) &&
_idNumberValidation.IsCitizen(_mainMember.IdNumber))
{
this.SelectedIdType = 1;
}
else if (!string.IsNullOrEmpty(_mainMember.IdNumber))
{
this.SelectedIdType = 2;
}
}
}
private void RaiseCommands(object value)
{
if (!string.IsNullOrEmpty(this.IdNumber))
{
if (!_salesValidation.IdNumberExists(this.IdNumber) && !this.HasErrors)
{
this.Aggregator.GetEvent<CanCreateNewMembership>().Publish(true);
}
else if (_salesValidation.IdNumberExists(this.IdNumber) &&
!_salesValidation.IncompleteApplication(this.IdNumber) &&
!_salesValidation.CanUpgrade(this.IdNumber) &&
!_salesValidation.CanReInstate(this.IdNumber))
{
//this.Aggregator.GetEvent<CanCreateNewMembership>().Publish(true);
}
else
{
this.Aggregator.GetEvent<CanCreateNewMembership>().Publish(false);
}
if (_salesValidation.IdNumberExists(this.IdNumber) &&
!this.HasErrors && _salesValidation.IncompleteApplication(this.IdNumber))
{
this.Aggregator.GetEvent<CanContinueEvent>().Publish(true);
}
else
{
this.Aggregator.GetEvent<CanContinueEvent>().Publish(false);
}
if (_salesValidation.IdNumberExists(this.IdNumber) &&
_salesValidation.CanUpgrade(this.IdNumber))
{
this.Aggregator.GetEvent<CanUpgradeEvent>().Publish(true);
}
else
{
this.Aggregator.GetEvent<CanUpgradeEvent>().Publish(false);
}
if (_salesValidation.IdNumberExists(this.IdNumber) &&
_salesValidation.CanReInstate(this.IdNumber))
{
this.Aggregator.GetEvent<CanReinstateEvent>().Publish(true);
}
else
{
this.Aggregator.GetEvent<CanReinstateEvent>().Publish(false);
}
if (this.HasErrors)
{
this.Aggregator.GetEvent<CanCreateNewMembership>().Publish(false);
this.Aggregator.GetEvent<CanContinueEvent>().Publish(false);
this.Aggregator.GetEvent<CanUpgradeEvent>().Publish(false);
this.Aggregator.GetEvent<CanReinstateEvent>().Publish(false);
}
}
}
private void Continue(string view)
{
if (view == ModuleViewConstants.PlanSelectionView)
this.Aggregator.GetEvent<ShowViewEvent>().Publish(
ModuleViewConstants.PlanSelectionView);
}
private void EventSubscriptions()
{
this.Aggregator.GetEvent<LoadLeadInfoEvent>().Subscribe(GetLeadInfo);
this.Aggregator.GetEvent<RaiseCommandAndEventsEvent>().Subscribe(RaiseCommands);
this.Aggregator.GetEvent<SearchEvent>().Subscribe(SearchedMembership);
this.Aggregator.GetEvent<ContinueEvent>().Subscribe(Continue);
this.Aggregator.GetEvent<SaveEvent>().Subscribe(SaveProgress);
}
bool INavigationAware.IsNavigationTarget(NavigationContext navigationContext)
{
_membership = GetMembership(navigationContext);
return _membership == null;
}
private Membership GetMembership(NavigationContext navigationContext)
{
if (navigationContext.NavigationService.Region.Context != null &&
navigationContext.NavigationService.Region.Context is Membership)
return (Membership)navigationContext.NavigationService.Region.Context;
return null;
}
void INavigationAware.OnNavigatedFrom(NavigationContext navigationContext)
{
var refId = (Thread.CurrentPrincipal as ICustomPrincipal).CustomIdentity.RefId;
this.SaveProgress(refId);
if (_membership != null)
{
navigationContext.NavigationService.Region.Context = _membership;
}
}
void INavigationAware.OnNavigatedTo(NavigationContext navigationContext)
{
}
private void SaveProgress(Guid refId)
{
var agentId = _uow.User.GetByRef(refId).Id;
_mainMember = new Principal();
if (_lead != null)
Mapper.Map(_lead, _mainMember);
if (_membership == null)
_membership = new Membership(
Guid.NewGuid(),
_lead.PlanId.HasValue?_lead.PlanId : null,
null,
null,
null,
DateTime.Now,
agentId,
_mainMember.Id,
(int)BillingStatusEnum.BAFP,
(int)MembershipStatusEnum.PWS,
null,
null,
null);
if (_mainMember != null)
{
//To Take out when Db is working
var principalId = _uow.Principal.GetAll().Max(x => x.Id);
_mainMember.Id = principalId + 1;
_membership.Principal = _mainMember;
}
//To Take out when Db is working
var id = _uow.Membership.GetAll().Max(x => x.Id);
_membership.Id = id + 1;
//===================================================\\
}
#endregion
#region Commands
#endregion
#region EventHandlers
#endregion
#region Constructors
public PreQualificationViewModel(
IEventAggregator aggregator,
IUnityContainer container,
IRegionManager regionManager,
IGetSavviUow uow,
IIdNumberValidation idNumberValidation,
ISalesValidation salesValidation) :
base(aggregator, container)
{
_uow = uow;
_regionManager = regionManager;
_principal = Thread.CurrentPrincipal as ICustomPrincipal;
_idNumberValidation = idNumberValidation;
_salesValidation = salesValidation;
EventSubscriptions();
this.GenderList = new ObservableCollection<string>()
{
"Male",
"Female"
};
}
#endregion
}
Please Help!!!

TableView with custom type combobox

I would like to create a TableView where its columns have reference to type:
private Indicators(String tl, WindowsItem chrt, String pne, Boolean sel) {
this.tool_col = new SimpleStringProperty(tl);
if (chrt == null) {
this.chart_col = new SimpleStringProperty("");
} else {
this.chart_col = new SimpleStringProperty(chrt.toString());
}
this.pane_col = new SimpleStringProperty(pne);
this.on_col = new SimpleBooleanProperty(sel);
this.chrt = chrt;
}
public String getTool() {
return tool_col.get();
}
public void setTool(String tl) {
tool_col.set(tl);
}
public WindowsItem getChart() {
return chrt;
}
public void setChart(WindowsItem _chrt) {
System.out.println("Indicators::setChart "+chrt.toString());
chrt = _chrt;
}
public String getPane() {
return pane_col.get();
}
public void setPane(String pne) {
pane_col.set(pne);
}
public Boolean getOn() {
return on_col.get();
}
public void setOn(boolean sel) {
on_col.set(sel);
}
public SimpleBooleanProperty onProperty() {
return on_col;
}
public SimpleStringProperty toolProperty() {
return tool_col;
}
public SimpleStringProperty chartProperty() {
return chart_col;
}
public SimpleStringProperty paneProperty() {
return pane_col;
}
}
I have a
private TableView<Indicators> tableviewIndicators;
In this column
private TableColumn<Indicators, WindowsItem> tablecolumnFrame;
public static class WindowsItem {
InternalWindow chrt;
private WindowsItem(InternalWindow _chrt) {
chrt = _chrt;
}
public String toString() {
return chrt.getTitle();
}
}
I would like to have a combobox or choicebox where every item type is
WindowsItem
How can I accomplish this?
I have tried this code
tablecolumnFrame.setCellFactory(new Callback<TableColumn<Indicators, WindowsItem>, TableCell<Indicators, WindowsItem>>() {
#Override
public TableCell<Indicators, WindowsItem> call(TableColumn<Indicators, WindowsItem> param) {
TableCell<Indicators, WindowsItem> cell = new TableCell<Indicators, WindowsItem>() {
#Override
public void updateItem(WindowsItem item, boolean empty) {
super.updateItem(item, empty);
if(empty){
return;
}
if (item != null) {
//final ChoiceBox<WindowsItem> choice = new ChoiceBox<>();
final ComboBox<WindowsItem> choice = new ComboBox<>();
int itemsInTab = chartsInTab.getChildren().size();
InternalWindow winItem;
for (int i = 0; i < itemsInTab; i++) {
if (chartsInTab.getChildren().get(i) instanceof InternalWindow) {
winItem = (InternalWindow) chartsInTab.getChildren().get(i);
choice.getItems().add(new WindowsItem(winItem));
//choice.getItems().add(winItem.toString());
System.out.println("winItem.toString() "+winItem.toString());
}
}
But it return this error
SEVERE: javafx.scene.control.Control loadSkinClass Failed to load skin 'StringProperty [bean: TableRow[id=null, styleClass=cell indexed-cell table-row-cell], name: skinClassName, value: com.sun.javafx.scene.control.skin.TableRowSkin]' for control TableRow[id=null, styleClass=cell indexed-cell table-row-cell]
You can try this:
private TableColumn<Indicators, WindowsItem> tablecolumnFrame;
and
public static class Indicators {
private final SimpleStringProperty tool_col;
private final SimpleStringProperty pane_col;
private final SimpleBooleanProperty on_col;
private final SimpleObjectProperty<WindowsItem> chrt;
private Indicators(String tl, WindowsItem chrt, String pne, Boolean sel) {
this.tool_col = new SimpleStringProperty(tl);
this.chrt = new SimpleObjectProperty<>(chrt);
this.pane_col = new SimpleStringProperty(pne);
this.on_col = new SimpleBooleanProperty(sel);
}
public String getTool() {
return tool_col.get();
}
public void setTool(String tl) {
tool_col.set(tl);
}
public WindowsItem getChart(){
return chrt.getValue();
}
public void setChart(WindowsItem _chrt) {
chrt.set(_chrt);
}
public String getPane() {
return pane_col.get();
}
public void setPane(String pne) {
pane_col.set(pne);
}
public Boolean getOn() {
return on_col.get();
}
public void setOn(boolean sel) {
on_col.set(sel);
}
public SimpleBooleanProperty onProperty() {
return on_col;
}
public SimpleStringProperty toolProperty() {
return tool_col;
}
public SimpleObjectProperty<WindowsItem> chartProperty() {
return chrt;
}
public SimpleStringProperty paneProperty() {
return pane_col;
}
}
be careful to:
public SimpleObjectProperty<WindowsItem> chartProperty() {
return chrt;
}
in your previous code was:
public SimpleStringProperty chartProperty() {
return chart_col;
}
this is the reason for the
SEVERE: javafx.scene.control.Control loadSkinClass Failed to load skin 'StringProperty

Nokia: Error preverifying class java/langnoclassdeffounderror : java/lang/comparable for java me platform

Getting error preverifying class java/langnoclassdeffounderror : java/lang/comparable for java me platform.
I have migrated my J2SE code to J2ME code. I am aware that some functions J2SE functions don't work on J2ME platform. Therefore, i have already crosschecked for the Comparable class. It is included in Java ME libraries.
Now, i am unable to resolve the errors. Please help me out here.
Please refer the code below:
import java.io.Serializable;
import aiproject.CompareToBuilder;
import aiproject.EqualsBuilder;
import aiproject.HashCodeBuilder;
import aiproject.ToStringBuilder;
public class WordProbability implements Comparable, Serializable {
private static final int UNDEFINED = -1;
private String word = "";
private String category = ICategorisedCategorizer.DEFAULT_CATEGORY;
private long matchingCount = UNDEFINED;
private long nonMatchingCount = UNDEFINED;
private double probability = ICategorizer.NEUTRAL_PROBABILITY;
public WordProbability() {
setMatchingCount(0);
setNonMatchingCount(0);
}
public WordProbability(String w) {
setWord(w);
setMatchingCount(0);
setNonMatchingCount(0);
}
public WordProbability(String c, String w) {
setCategory(c);
setWord(w);
setMatchingCount(0);
setNonMatchingCount(0);
}
public WordProbability(String w, double probability) {
setWord(w);
setProbability(probability);
}
public WordProbability(String w, long matchingCount, long nonMatchingCount) {
setWord(w);
setMatchingCount(matchingCount);
setNonMatchingCount(nonMatchingCount);
}
public void setWord(String w) {
this.word = w;
}
public void setCategory(String category) {
this.category = category;
}
public void setProbability(double probability) {
this.probability = probability;
this.matchingCount = UNDEFINED;
this.nonMatchingCount = UNDEFINED;
}
public void setMatchingCount(long matchingCount) {
if (matchingCount < 0) {
throw new IllegalArgumentException("matchingCount must be greater than 0");
}
this.matchingCount = matchingCount;
calculateProbability();
}
public void setNonMatchingCount(long nonMatchingCount) {
if (nonMatchingCount < 0) {
throw new IllegalArgumentException("nonMatchingCount must be greater than 0");
}
this.nonMatchingCount = nonMatchingCount;
calculateProbability();
}
public void registerMatch() {
if (matchingCount == Long.MAX_VALUE) {
throw new UnsupportedOperationException("Long.MAX_VALUE reached, can't register more matches");
}
matchingCount++;
calculateProbability();
}
public void registerNonMatch() {
if (nonMatchingCount == Long.MAX_VALUE) {
throw new UnsupportedOperationException("Long.MAX_VALUE reached, can't register more matches");
}
nonMatchingCount++;
calculateProbability();
}
private void calculateProbability() {
String method = "calculateProbability() ";
double result = ICategorizer.NEUTRAL_PROBABILITY;
if (matchingCount == 0) {
if (nonMatchingCount == 0) {
result = ICategorizer.NEUTRAL_PROBABILITY;
} else {
result = ICategorizer.LOWER_BOUND;
}
} else {
result = BayesianCategorizer.normaliseSignificance((double) matchingCount / (double) (matchingCount + nonMatchingCount));
}
probability = result;
}
/**
* output
*/
public double getProbability() {
return probability;
}
public long getMatchingCount() {
if (matchingCount == UNDEFINED) {
throw new UnsupportedOperationException("MatchingCount has not been defined");
}
return matchingCount;
}
public long getNonMatchingCount() {
if (nonMatchingCount == UNDEFINED) {
throw new UnsupportedOperationException("nonMatchingCount has not been defined");
}
return nonMatchingCount;
}
public String getWord() {
return word;
}
public String getCategory() {
return category;
}
public boolean equals(Object o) {
if (!(o instanceof WordProbability)) {
return false;
}
WordProbability rhs = (WordProbability) o;
return new EqualsBuilder().append(getWord(), rhs.getWord()).append(getCategory(), rhs.getCategory()).isEquals();
}
public int compareTo(java.lang.Object o) {
if (!(o instanceof WordProbability)) {
throw new ClassCastException(o.getClass() + " is not a " + this.getClass());
}
WordProbability rhs = (WordProbability) o;
return new CompareToBuilder().append(this.getCategory(), rhs.getCategory()).append(this.getWord(), rhs.getWord()).toComparison();
}
public String toString() {
return new ToStringBuilder(this).append("word", word).append("category", category).append("probability", probability).append("matchingCount", matchingCount).append("nonMatchingCount", nonMatchingCount).toString();
}
public int hashCode() {
return new HashCodeBuilder(17, 37).append(word).append(category).toHashCode();
}
}
I don't see a Comparable in the javadocs of JavaME.
So I think it is not there.
Where did you found it?
Maybe some Lib or JSR has included it. Than you need to include this in the project settings.
If you just need the interface, you can define it yourself.

mvvm how to pass data from one view model to another view model

I have One View which has one Data grid with radio Button , onchecking radio Box , the selected row should go to other View Screen Textbox
here is my first ViewModel
public class CampaignSearchResultsViewModel : ViewModelBase
{
public CampaignSearchResultsViewModel(List<Lead> obj)
{
foreach(Lead lead in obj)
{
SelectedLead = lead;
}
}
public CampaignSearchResultsViewModel()
{
this.Commands.Add("CheckedCommand", new ActionCommand<Lead>(CheckIt));
Commands.Add("OutboundSelect", new ActionCommand<Object>(OutboundSelection));
_leads = new ObservableCollection<Lead>();
}
public ICommand OutboundSelect
{
get
{
return Commands["OutboundSelect"];
}
}
public void OutboundSelection(Object obj)
{
}
private void CheckIt(Lead lead)
{
SelectedLead = lead;
LeadViewModel lmv = new LeadViewModel(this);
}
#region Private
private ObservableCollection<Lead> _leads;
public bool IsChecked { get; set; }
private ICommand _checkedCommand;
private object _testProperty;
private Lead _selectedLead;
private ICollectionView icv;
#endregion
private ICommand _checkedRadioCommand;
private bool _inboundChecked;
#region Properties
public ObservableCollection<Lead> Leads
{
get { return _leads; }
set
{
_leads = value;
FirePropertyChanged("Leads");
}
}
public Lead SelectedLead
{
get { return _selectedLead; }
set { _selectedLead = value; }
}
public ICommand CheckedCommand
{
get
{
return Commands["CheckedCommand"];
}
}
public bool InboundChecked
{
get
{
return _inboundChecked;
}
private set
{
if (_inboundChecked != value)
{
_inboundChecked = value;
FirePropertyChanged("InboundChecked");
}
}
}
#endregion
}
i have to map SelectedLead to the other view model i have pass info to SearchCampaignMembers() method , how
public partial class LeadViewModel : ViewModelBase
{
public void SearchCampaignMembers()
{
_service.Load(_service.SearchCampaignMembersQuery(Entity.FirstName, Entity.LastName), lo =>
{
if (!lo.HasError)
{
ListLead = lo.Entities.ToList();
_savedLeadStatusId = Entity.LeadStatusId;
EntitySet = _service.Leads;
if (ListLead.Count == 1)
{
if (Entity != null)
{
IsVendorLead = Entity.LeadTypeId == Lookups.LeadType.VendorLead;
//Lead Update History
EntityQuery<LeadUpdateHistory> historyquery = null;
historyquery = _service.GetLeadUpdateHistoryByLeadIdQuery(Entity.LeadId);
_service.Load(historyquery, l =>
{
if (!l.HasError)
{
EntityHistory = _service.LeadUpdateHistories;
}
}, null);
//Lead Assignment
EntityQuery<LeadsAssignment> assignmentquery = null;
assignmentquery = _service.GetLeadsAssignmentByLeadIdQuery(Entity.LeadId);
_service.Load(assignmentquery, l =>
{
if (!l.HasError)
{
EntityAssignment = _service.LeadsAssignments;
}
}, null);
if (Entity.LeadTypeId == Lookups.LeadType.PhoneLead)
{
IsInboundLead = Entity.VendorId == null;
IsOutboundLead = Entity.VendorId != null;
}
else
{
IsInboundLead = false;
IsOutboundLead = false;
}
//SelectTimeToCall(Entity);
if (IsOutboundLead)
SelectedCampaign = Entity.LeadCampaigns.FirstOrDefault().Campaign;
else
SelectCampaign(Entity);
OperationsListener listener = new OperationsListener();
listener.Completed += (s, args) =>
{
CompleteInitializing();
//SwitchTab(param.InitialTab);
Action action = () =>
{
SelectDealer(Entity);
};
//GetDealerRecommendation(Entity.Address.ZipCode, action);
SelectStatus(Entity);
//if (callback != null)
// callback();
};
LoadLookupData(listener);
listener.Start();
}
}
else if (ListLead.Count >= 1)
{
CampaignSearchResultsViewModel vm = new CampaignSearchResultsViewModel();
foreach (Lead lead in ListLead)
{
vm.Leads.Add(lead);
ObservableCollection<Lead> abc;
abc = new ObservableCollection<Server.DataAccess.Lead>();
}
ViewController.OpenDialog("SearchCampaignResults", vm, r =>
{
});
}
else if (ListLead.Count == 0)
{
ViewController.OpenDialog("NoResults", (r) =>
{
});
}
}
else
{
//if (callback != null)
// callback();
}
}, null);
}
}
If you use MVVM Light Toolkit, see Messenger class see this answer for sample.

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