Vaadin Accordian Component

Vaadin Accordian Component

Accordion is a multicomponent container similar to TabSheet, except that the “tabs” are arranged vertically. Clicking on a tab opens its contained component in the space between the tab and the next one. You can use an Accordion identically to a TabSheet, which it actually inherits. .. more info vaadin page


1.) Here are the Source Codes that inspired from valo-demo site:

accordian.jpg

2.) AccordianForm.java

import com.vaadin.navigator.View;
import com.vaadin.navigator.ViewChangeListener.ViewChangeEvent;
import com.vaadin.ui.Accordion;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.VerticalLayout;
import net.fndong.ui.Menu;

/**
 * @author fndong Sep 15, 2016
 * AccordianForm.java
 */
public class AccordianForm extends VerticalLayout implements View {
    /* (non-Javadoc)
     * @see com.vaadin.navigator.View#enter(com.vaadin.navigator.ViewChangeListener.ViewChangeEvent)
     */
    private HorizontalLayout hLayout;
    private VerticalLayout vLayout;
    private Label lbltitle;
    private Accordion accFaith;
    
    @Override
    public void enter(ViewChangeEvent event) {
    }
    
    // constructor()
    public AccordianForm(){
        setMargin(true);
        initComponents();
        initLayout();
    }
    
    // init for the vaadin components
    private void initComponents(){
        vLayout = new  VerticalLayout();
        vLayout.addComponent(new Menu());
        hLayout = new HorizontalLayout();
        hLayout.setSpacing(true);
        hLayout.setWidth("100%");
        lbltitle = new Label("Form Accordians");
        
        // set Accordian
        accFaith = getAccordianFaith();
        
    }
    
// accordian set values on Tab Accordian
    Accordion getAccordianFaith(){
        TestIcon testIcon = new TestIcon(0);
        Accordion acESV = new Accordion();
        acESV.setCaption("Bible ESV Online");
        
        acESV.addTab(new VerticalLayout() {
            {
                setMargin(true);
                addComponent(new Label(
                        "The Genealogy of Jesus Christ : 1The book of the genealogy of Jesus Christ, the son of David, the son of Abraham. 2 Abraham was the father of Isaac, and Isaac the father of Jacob, and Jacob the father of Judah and his brothers, 3and Judah the father of Perez and Zerah by Tamar, and Perez the father of Hezron, and Hezron the father of Ram, 4and Ram the father of Amminadab, and Amminadab the father of Nahshon, and Nahshon the father of Salmon, 5 and Salmon the father of Boaz by Rahab, and Boaz the father of Obed by Ruth, and Obed the father of Jesse, 6and Jesse the father of David the king. "));
            }
        }, "Mathew 1 ", testIcon.get());
        acESV.addTab(new VerticalLayout() {
            {
                setMargin(true);
                addComponent(new Label(
                        "The Visit of the Wise Men : 1Now after Jesus was born in Bethlehem of Judea in the days of Herod the king, behold, wise men from the east came to Jerusalem, 2saying, Where is he who has been born king of the Jews? For we saw his star when it rose and have come to worship him. 3When Herod the king heard this, he was troubled, and all Jerusalem with him; 4and assembling all the chief priests and scribes of the people, he inquired of them where the Christ was to be born. 5They told him, In Bethlehem of Judea, for so it is written by the prophet: "));
            }
        }, "Mathew 2 ", testIcon.get());
        acESV.addTab(new VerticalLayout() {
            {    
                setMargin(true);
                addComponent(new Label(
                        "John the Baptist Prepares the Way : 1In those days John the Baptist came preaching in the wilderness of Judea, 2 Repent, for the kingdom of heaven is at hand. 3For this is he who was spoken of by the prophet Isaiah when he said,The voice of one crying in the wilderness: Prepare the way of the Lord; make his paths straight."));
            }
        }, "Mathew 3 ", testIcon.get());
          
        return acESV;
    }
    
    
    // vaadin addcomponent to layout
    private void initLayout(){
        hLayout.addComponent(lbltitle);
        hLayout.addComponent(accFaith);
        addComponent(vLayout);
        addComponent(hLayout);
    }

}

 2.) TesIcon.java ( from vaadin source code )

 

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import com.vaadin.server.FontAwesome;
import com.vaadin.server.Resource;
import com.vaadin.server.ThemeResource;

/**
 *
 * @since
 * @author Vaadin Ltd
 */
public class TestIcon {

    int iconCount = 0;

    public TestIcon(int startIndex) {
        iconCount = startIndex;
    }

    public Resource get() {
        return get(false, 32);
    }

    public Resource get(boolean isImage) {
        return get(isImage, 32);
    }

    public Resource get(boolean isImage, int imageSize) {
        if (!isImage) {
            if (++iconCount >= ICONS.size()) {
                iconCount = 0;
            }
            return ICONS.get(iconCount);
        }
        return new ThemeResource("../runo/icons/" + imageSize + "/document.png");
    }

    static List ICONS = Collections.unmodifiableList(Arrays
            .asList(FontAwesome.values()));

}

 

Selamat Mencuba / Give A try / Agi idup must try…

How to integrate Vaadin with javascript – add JavaScript Connector?

How to integrate Vaadin with javascript – add JavaScript Connector?

package_js.jpg

  1. JSIntegrationComp.java ( – to viewing our components & call the javascript method from java – MyComponent.java)
import com.vaadin.navigator.View;
import com.vaadin.navigator.ViewChangeListener.ViewChangeEvent;
import com.vaadin.ui.CssLayout;

@SuppressWarnings("serial")
public class JSIntegrationComp  extends CssLayout implements View{
	MyComponent mycomponent = new MyComponent();
	
	public JSIntegrationComp() {

		// Process a value input by the user from the client-side
		mycomponent = new MyComponent();    
		addComponent(mycomponent);
		
	}
}

2. MyComponent.java

import com.vaadin.ui.AbstractJavaScriptComponent;

@SuppressWarnings("serial")
@JavaScript({"mylibrary.js", "mycomponent-connector.js"})
public class MyComponent extends AbstractJavaScriptComponent {
	 @Override
     protected MyComponentState getState() {
         return (MyComponentState) super.getState();
     }
}

3. MyComponentState.java

public class MyComponentState extends JavaScriptComponentState {
     private static final long serialVersionUID = 1L;
}

 4. mycomponent-connector.js (javascript)

window.net_fndong_js_MyComponent =
function() {
    var mycomponent = new mylibrary.Comp(this.getElement());

    this.onStateChange = function(e) {};

};

5. mylibrary.js (javascript)

var mylibrary = mylibrary || {};

mylibrary.Comp = function(element) {
    element.innerHTML = "hello";};

 

 

 

How to add javascript in vaadin (Simple Example)?

How to add javascript in vaadin? – 13/9/2016 – My study notes:

  1. Simple example with Javascript on Vaadin .

pop_vaadin_js.jpg

  1. First create the class that will call javascript:
import com.vaadin.annotations.JavaScript;
import com.vaadin.navigator.View;
import com.vaadin.navigator.ViewChangeListener.ViewChangeEvent;
import com.vaadin.server.Page;
import com.vaadin.ui.Button;

@JavaScript({ "vaadin://js/test.js" })
@SuppressWarnings("serial")
public class LayoutForFormView extends LayoutForForm implements View {
private Button button;
@Override
    public void enter(ViewChangeEvent event) {
        // TODO Auto-generated method stub
        
    }

    public LayoutForFormView() {
        // TODO Auto-generated constructor stub
        setSizeFull();

         String test = "Test Only";
         button = new Button("Show Me!");
            button.addClickListener(new Button.ClickListener() {
                public void buttonClick(ClickEvent event) {
               Page.getCurrent().getJavaScript()
               .execute("showmessage('" + "test" + "')");
                }
            });
            
            addComponent(button);
    }

  • vaadin://js/test.js

-. To make sure the location of javascript can be called, make sure to add vaadin , it will automatically referring from this path:

js_loc.jpg

Javascript : test.js

function showmessage(message)
{
    alert("you should see this : "+message);
}

 

How to set the default value into combobox – Vaadin

How to set default value into combobox :

Here is my source codes, i would like make the values that passing from method getGender():

// generate Genders into combobox value
Collection<GenderTable> gendertable= getRecordGenders();
Container container= new ListContainer<RefGenders>(GenderTable.class, genderTable);
combobox_gender.setContainerDataSource(container);
combobox_gender.setItemCaptionPropertyId("nameGender");

noid_textfield.addValueChangeListener(new ValueChangeListener() {
@Override
public void valueChange(ValueChangeEvent event) {
String gender = getGenders(); // returning gender code , F - Female or M - Male
String genderName = "";

if("F".equalsIgnoreCase(gender)){
genderName ="Female";
}else{
genderName ="Male";
}

GenderTable genderTable = new RefGenders(gender, genderName);
PropertysetItem item = new ProppertysetItme();
FieldGroup binder = new FieldGroup(item);
binder(combobox_gender , "GenderTable");
}
});

The result at display page , the Combobox Gender – “combobox_gender” are gray. and its not bind property. any solution that can fix this.

whycombogray

Solution 1 :

1.using gender_combo.setValue(gender_combo.getItemIds().iterator().next()); – to make a default value for ComboBox .

 

Solution 2 :

2. using below code by iterate the combobox value.

@Override
public void valueChange(ValueChangeEvent event) {
 @SuppressWarnings("unchecked")
 Iterator<GenderTable> iterator = (Iterator<GenderTable>) 
 combobox_gender.getItemIds().iterator();
              
              while(iterator.hasNext()) {
                     GenderTable obj = iterator.next();
// getGender - get return value , F - Female , M - Male
                     if(obj.getcodeGender().equals(getGender().trim())){
                         gender_combo.setValue(obj);
                         break;
                     }
                     }
});

SELAMAT MENCUBA! / ABA MAYA WANG ADEP IRA CUBA!

Vaadin – set Age into TextField from value Date – Popup PopupDateField

Vaadin – set Age value into TextField from value Date – Popup PopupDateField

datetoAge

1). First, create Simple vaadin project , just right click create Vaadin 7 Project (Maven).

2).  Class MyUI.java , declare Components PopupDateField – dateBirth , and TextField – ageField.

3). Source code MyUI.java.

@Theme("mytheme")
@Widgetset("com.example.testVaadin.MyAppWidgetset")
public class MyUI extends UI {
 private PopupDateField dateBirth;
 private String strAge;
 private TextField ageField;
 private FormLayout formLayout;
 private FieldGroup binder;
//Have an item
PropertysetItem item;
 @Override
 protected void init(VaadinRequest vaadinRequest) {
 final VerticalLayout layout = new VerticalLayout();
 formLayout = new FormLayout();
 // date PopupField
 dateBirth = new PopupDateField("Date :");
 dateBirth.setDateFormat("dd-MM-yyyy");
 dateBirth.addStyleName("tiny");
 dateBirth.setWidth("10em");
 // age textField
 ageField = new TextField("Age :");
 ageField.addStyleName("tiny");
 ageField.setWidth("10em");
 listenerComponent();
 
 formLayout.addComponents(dateBirth,ageField);
 layout.addComponents(formLayout);
 layout.setMargin(true);
 layout.setSpacing(true);
 
 setContent(layout);
 }

 @WebServlet(urlPatterns = "/*", name = "MyUIServlet", asyncSupported = true)
 @VaadinServletConfiguration(ui = MyUI.class, productionMode = false)
 public static class MyUIServlet extends VaadinServlet {
 }
 
 @SuppressWarnings("deprecation")
 public void listenerComponent() {
 item = new PropertysetItem();
 
 dateBirth.addValueChangeListener(new PopupDateField.ValueChangeListener() {
 @Override
 public void valueChange(ValueChangeEvent event) {
 strAge = getPersonAge((Date)event.getProperty().getValue());
 System.out.println(" ageBirthDate : " + strAge); 
 item.addItemProperty("age", new ObjectProperty<String>(strAge));
 binder = new FieldGroup(item);
 binder.bind(ageField, "age");
 }
 });
 
 }
 
 public String getPersonAge(Date birthDate) {
 // convert date to stringDateFormat MM-dd-yyyy
 SimpleDateFormat formatter = new SimpleDateFormat("MM-dd-yyyy");
 // convert simpleDateFormat to string
 String dateStr = formatter.format(birthDate);
 System.out.println("date String : " + dateStr);
 
 Calendar birth = new GregorianCalendar();
 Calendar today = new GregorianCalendar();
 int age = 0;
 int factor = 0; 
//calculate age
 try {

 Date birthDt = new SimpleDateFormat("MM-dd-yyyy").parse(dateStr);
 Date currentDate = new Date(); //current date
 
 birth.setTime(birthDt);
 today.setTime(currentDate);
 
 // check if birthday has been celebrated this year
 if(today.get(Calendar.DAY_OF_YEAR) < birth.get(Calendar.DAY_OF_YEAR)) {
 factor = -1;
 //birthday not celebrated
 }
 age = today.get(Calendar.YEAR) - birth.get(Calendar.YEAR) + factor;
 } catch (ParseException e) {
    e.printStackTrace();
 } 

 return String.valueOf(age);
 }

 

4) I Used Simple Binding to bind to Field Age TextField from value Date Component PopupDateField .

PropertysetItem item = new PropertysetItem();
// remove item property by Object id "age"
item.removeItemProperty("age");
item.addItemProperty("age", new ObjectProperty<String>(strAge));
FieldGroup  binder = new FieldGroup(item);
binder.bind(ageField, "age");

Vaadin – How to Add java.util.Map key & values into ComboBox Component

Good Day!

  1. Title : Vaadin – How to Add java.util.Map key & values into ComboBox Component:

months_combobx.jpg

1). Method to return ComboBox values

private ComboBox setComboMonthsValue() {
        String monthname = “”;
        Map<Integer, String> mapMonths = new HashMap<Integer, String>();
        ComboBox monthsCombo = new ComboBox(“months“); // combox box months
        GregorianCalendar today = new GregorianCalendar();
        int todayMonth = today.get(java.util.Calendar.MONTH); // jan = 0, not 1
        // set default value based on month today.
        mapMonths = getMonthsName();

        if (mapMonths != null) {
                for (Entry<Integer, String> enumEntry : mapMonths.entrySet()) {
                    monthsCombo.addItem(enumEntry.getKey());
                  if (enumEntry.getValue() != null) {
                      monthsCombo.setItemCaption(enumEntry.getKey(),enumEntry.getValue());
                  }
                }
              }
         return monthsCombo;
    }

    // return map, generate record for months
    private Map<Integer, String> getMonthsName(){
        Map<Integer, String> map = new HashMap<Integer, String>();
        
        String[] monthslist = new DateFormatSymbols().getMonths();
        System.out.println(” count : ” + monthslist.length);
        for (int i = 0; i < monthslist.length; i++) {
          String month = monthslist[i];
          map.put(i, month);
        }
        return map;
    }

2. To add Default value in Combobox, by using method .setInputPrompt(“value”):

monthsCombo.setInputPrompt(“Jun”);

 

Vaadin – How to make Alignment combobox with button.

Good Day!

Title : Vaadin – How to make Alignment combobox with button.

1.The button are not align with combobox , where button are hanging on the top if we using HorizontalLayout , so my solution is using  GridLayout.

  • added with : grid.setComponentAlignment(btnSubmit,Alignment.BOTTOM_LEFT);

2. From Image  A to Image B.

3. Image A

howtosetalignthecomboboxandbutton2.jpg

To 

4. Image B

howtosetalignthecomboboxandbutton.jpg

5. The source Code.

protected void init(VaadinRequest request) {

final VerticalLayout layout = new VerticalLayout();
layout.setMargin(true);
setContent(layout);

GridLayout grid = new GridLayout(3,1);
Button btnSubmit = new Button(“Submit“);
combofirst= createFirstComboSelect(); // state combobox
combosecond = createSecondComboSelect(); // district combobox
grid.setSpacing(true);
grid.setSizeFull();
grid.setSizeUndefined();
grid.addComponent(combofirst);
grid.addComponent(combosecond);
grid.addComponent(btnSubmit);
/***java.lang.IllegalArgumentException: Component must be added to layout before using setComponentAlignment() ***/
grid.setComponentAlignment(btnSubmit,Alignment.BOTTOM_LEFT);
layout.addComponent(grid);
}

6. Full source codes project can get from My Github.