0

How to programmatically create and post a SelectEvent for use with a Combobox?

asked 2012-07-27 14:29:25 +0800

s3lvatico gravatar image s3lvatico
22 2

Hello everyone,

I'm using a already populated combobox with a prefilled model that is always non-empty.
At a certain point I need to fire a selection event, so that the event handler associated with the combobox is invoked, but I'm quite confused about the construction of the SelectEvent<T, E> object.

Here's the event listener

 @Listen("onSelect=#cmbMyCombobox")
   public void onMyComboboxSelection(SelectEvent<Combobox, MyObject> evtSelect) {
      Set<MyObject> selectedObjects = evtSelect.getSelectedObjects();
      int size = selectedObjects.size();
      MyObject selectedStuff= selectedObjects.toArray(new MyObject[ size ])[0];
     // do things with the selectedStuff
   }

And here's the method that tries to fire the event

private void fireFirstPowuaServerSelectionEvent() {
      ListModel<MyObject> model = (ListModel<MyObject>) cmbMyCombobox.getModel();
      MyObject stuffIWantToSelect = model.getElementAt(0);

      Set<MyObject> selectedItems= new HashSet<MyObject>();
      selectedItems.add(stuffIWantToSelect);
      SelectEvent<Combobox, MyObject> evtSelection = new SelectEvent<Combobox, MyObject>( ... ? ...);
      Events.echoEvent(evtSelection);
   }

Main questions are:
1- what is the appropriate constructor I should use?
2- one of the constructors need a set of selected *ITEMS* and a set of selected *OBJECTS*. What is the difference between them? Are the items the combo items? Is the items set nullable?
3- the longest constructor includes a "ref" parameter. What is it for?

Thanks in advance

delete flag offensive retag edit

1 Reply

Sort by » oldest newest

answered 2012-07-27 21:04:46 +0800

marcelodecampos gravatar image marcelodecampos
183

How about this:


The code below is an example of Combobox derived class, that use an EJB Session Bean ( <BEAN> ) and EJB EntityBean( <Data> which is a POJO too)

public abstract class ComboboxExt<BEAN, DATA> extends Combobox
{
	private static final Logger logger = LoggerFactory.getLogger( ComboboxExt.class );
	private static final long serialVersionUID = 5803878398952556887L;
	private Class<BEAN> persistentClass;
	private transient BEAN session = null;

	private List<DetailInterface> details;

	protected abstract Class<BEAN> getSessionClass( );

	protected abstract void load( );

	public ComboboxExt( )
	{
		super( );
		setPersistentClass( );
	}

	public ComboboxExt( String value ) throws WrongValueException
	{
		super( value );
		setPersistentClass( );
	}

	@Override
	public void setSelectedItem( Comboitem item )
	{
		logger.info( "setSelectedItem: " + item.getValue( ).toString( ) );
		super.setSelectedItem( item );
		processOnSelect( );
	}

	private void processOnSelect( )
	{
		logger.info( "processOnSelect: " + this.getClass( ).getSimpleName( ) );
		Events.sendEvent( this, new Event( Events.ON_SELECT, this ) );
	}

	public DATA getSelectedValue( )
	{
		Comboitem item = getSelectedItem( );

		if ( item != null && item.getValue( ) != null ) {
			return item.getValue( );
		}
		else {
			return null;
		}
	}

	public void load( List<DATA> list, DATA itemToSelect, boolean bSelectFirst )
	{
		getChildren( ).clear( );
		if ( SysUtils.isEmpty( list ) == false ) {
			Comboitem selectedItem = null;

			for ( DATA dto : list ) {
				Comboitem item = appendItem( dto.toString( ) );
				if ( item != null ) {
					item.setValue( dto );
					if ( itemToSelect != null && item.equals( itemToSelect ) ) {
						selectedItem = item;
					}
				}
			}
			if ( selectedItem != null ) {
				setSelectedItem( selectedItem );
			}
			else {
				if ( bSelectFirst ) {
					setSelectedIndex( 0 );
				}
			}
		}
	}

	protected void setPersistentClass( )
	{
		this.persistentClass = getSessionClass( );
	}

	@SuppressWarnings( "unchecked" )
	public BEAN getSession( )
	{
		try {
			if ( this.session == null ) {
				this.session = ( (BEAN) ServiceLocator.getInstance( ).getRemoteSession( this.persistentClass ) );
			}
		}
		catch ( NamingException e ) {
			e.printStackTrace( );
		}
		return this.session;
	}

	public void find( DATA item )
	{
		if ( getItemCount( ) <= 0 || item == null ) {
			return;
		}
		logger.info( "Looking for: " + item.toString( ) );
		for ( Component child : getChildren( ) ) {
			if ( child instanceof Comboitem ) {
				Comboitem cbItem = (Comboitem) child;
				if ( cbItem.getValue( ).equals( item ) ) {
					setSelectedItem( cbItem );
					break;
				}
			}
		}
	}

	private List<DetailInterface> getDetails( )
	{
		if ( this.details == null ) {
			this.details = new ArrayList<DetailInterface>( );
		}
		return this.details;
	}

	public void addDetail( DetailInterface newDetail )
	{
		getDetails( ).add( newDetail );
	}

	public void onSelect( Event evt )
	{
		logger.info( "onSelect: " + evt.getTarget( ).getId( ) );
		for ( DetailInterface item : getDetails( ) ) {
			item.onChangeMaster( getSelectedValue( ) );
		}
		evt.stopPropagation( );
	}

	public void onCreate( Event evt )
	{
		if ( ( this instanceof DetailInterface ) == false && this.getItemCount( ) == 0 )
		{
			logger.info( "onCreate calling load: " + evt.getTarget( ).getId( ) );
			load( );
		}
	}
}


This is where I send a select event

private void processOnSelect( )
{
	logger.info( "processOnSelect: " + this.getClass( ).getSimpleName( ) );
	Events.sendEvent( this, new Event( Events.ON_SELECT, this ) );
}

As you can see, this is an abstract class, so this is an example of it

public class CityCombobox extends ComboboxExt<CitySession, City> implements DetailInterface
{
	private static final Logger logger = LoggerFactory.getLogger( CityCombobox.class );
	private static final long serialVersionUID = 1180477829375738059L;

	@Override
	public void onChangeMaster( Object master )
	{
		logger.info( "onChangeMaster" );
		load( ( (State) master ) );
	}

	public void load( State state )
	{
		logger.info( String.format( "load(%s)", state.getDescription( ) ) );
		load( getSession( ).getAll( state ), null, true );
	}

	@Override
	protected Class<CitySession> getSessionClass( )
	{
		return CitySession.class;
	}

	@Override
	protected void load( )
	{
	}
}


or

public class GenderCombobox extends ComboboxExt<GenderSession, Gender>
{
	private static final Logger logger = LoggerFactory.getLogger( GenderCombobox.class );
	private static final long serialVersionUID = -7706250007578273124L;

	@Override
	protected Class<GenderSession> getSessionClass( )
	{
		return GenderSession.class;
	}

	@Override
	public void load( )
	{
		logger.info( "load" );
		load( ( (List<Gender>) getSession( ).getAll( ) ), null, true );
	}
}

going on.... gender is just and EJB Entity Bean

@Entity
@NamedQueries( { @NamedQuery( name = "Gender.findAll", query = "select o from Gender o" ) } )
@Table( name = "\"gender\"" )
public class Gender extends SimpleTable<Gender>
{
	private static final long serialVersionUID = 3372468873867948006L;
	@Column( name = "gnd_description_ch", nullable = false )
	private String description;
	@Id
	@Column( name = "gnd_id_in", nullable = false )
	private Integer id;


	@Override
	public String getDescription()
	{
		return this.description;
	}

	@Override
	public void setDescription( String gnd_description_ch )
	{
		this.description = gnd_description_ch;
	}

	@Override
	public Integer getId()
	{
		return this.id;
	}

	@Override
	public void setId( Integer gnd_id_in )
	{
		this.id = gnd_id_in;
	}
}


How to use it: use 'use'!!!!

<?xml version="1.0" encoding="UTF-8"?>
<zk xmlns="http://www.zkoss.org/2005/zul" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.zkoss.org/2005/zul http://www.zkoss.org/2005/zul/zul.xsd ">
	<grid fixedLayout="true">
	    <columns>
	        <column width="20%"/>
	        <column/>
	    </columns>
	    <rows>
	        <row>
	            <label value="CPF" />
	            <textbox id="cpf" width="200px" maxlength="14" />
	        </row>
	        <row>
	            <label value="Nome Completo" />
	            <textbox id="name" hflex = "1" maxlength="128" />
	        </row>
	        <row>
	            <label value="Sexo" />
	            <combobox id="gender" width="200px" readonly="true" use= "br.com.mcampos.web.core.combobox.GenderCombobox"/>
	        </row>
	        <row>
	            <label value="Tratamento" />
	            <combobox id="title" width="200px" readonly="true" use="br.com.mcampos.web.core.combobox.TitleCombobox"/>
	        </row>
	        <row>
	            <label value="Estado Civil"/>
	            <combobox id="maritalStatus" width="200px" readonly="true" use="br.com.mcampos.web.core.combobox.CivilStateCombobox"/>
	        </row>
	        <row>
	            <label value="Data Nascimento"/>
	            <hlayout valign="middle">
	                <datebox id="birthdate" format="dd/MM/yyyy"/>
	                   <label value="DD/MM/YYYY. Ex.: 25/12/2009"/>
	            </hlayout>
	        </row>
	        <row>
	            <label value="Naturalidade"/>
	            <vbox width="100%">
	                <combobox id="bornState" width="300px" readonly="true" use="br.com.mcampos.web.core.combobox.StateCombobox" />
	                <combobox id="bornCity" width="500px" readonly="true" use="br.com.mcampos.web.core.combobox.CityCombobox"/>
	            </vbox>
	        </row>
	        <row>
	            <label value="Nome do Pai"/>
	            <textbox id="fatherName" hflex = "1" maxlength="128"/>
	        </row>
	        <row>
	            <label value="Nome da Mãe"/>
	            <textbox id="motherName" hflex = "1" maxlength="128"/>
	        </row>
	    </rows>
	</grid>
</zk>

link publish delete flag offensive edit
Your reply
Please start posting your answer anonymously - your answer will be saved within the current session and published after you log in or create a new account. Please try to give a substantial answer, for discussions, please use comments and please do remember to vote (after you log in)!

[hide preview]

Question tools

Follow

RSS

Stats

Asked: 2012-07-27 14:29:25 +0800

Seen: 231 times

Last updated: Jul 27 '12

Support Options
  • Email Support
  • Training
  • Consulting
  • Outsourcing
Learn More