Align DynamicForm Horizontally to the Center of VLayout - smartgwt

Is there any possible way to align horizontally a DynamicForm to the center of a VLayout? I've tried what is done in this showcase demo, but it won't work for the form (it does work correctly for the IButton).
Here is my code:
public class PreferencesStackSection extends SectionStackSection {
private static final String SAVE_ICON = "icons/save.png";
private static final int COMPONENT_GAP = 10;
// Object used to get access to internationalization constants and messages
private BMSimulatorConstants constants = GWT.create(BMSimulatorConstants.class);
private DataSource ds;
private DynamicForm form;
private IButton saveBtn;
public PreferencesStackSection(String title) {
super(title);
ds = DataSource.get("preferences");
buildPreferencesLayout();
}
private void buildPreferencesLayout() {
VLayout layout = new VLayout(COMPONENT_GAP);
layout.setMargin(COMPONENT_GAP * 2);
layout.setDefaultLayoutAlign(Alignment.CENTER);
createPreferencesForm(layout);
createSaveButton(layout);
this.addItem(layout);
}
private void createPreferencesForm(VLayout layout) {
form = new DynamicForm();
form.setNumCols(1);
form.setTitleOrientation(TitleOrientation.TOP);
form.setDataSource(ds);
layout.addMember(form);
}
private void createSaveButton(VLayout layout) {
saveBtn = new IButton(constants.preferencesSaveButton());
saveBtn.setIcon(SAVE_ICON);
saveBtn.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
DSCallback callback = new DSCallback() {
public void execute(DSResponse response, Object rawData, DSRequest request){
SC.say(constants.preferencesSavedOK());
}
};
form.saveData(callback);
}
});
layout.addMember(saveBtn);
}
}

This solved the problem (the order of the lines is really important for it to work):
private void createPreferencesForm(VLayout layout) {
form = new DynamicForm();
form.setDataSource(ds);
form.setNumCols(1);
form.setTitleOrientation(TitleOrientation.TOP);
layout.addMember(form);
form.setWidth("70%");
for(FormItem item: form.getFields()){
item.setWidth("*");
}
}

Related

Filter ListView with SearchView xamarin

I want to filter Listview by Searchview
I use the following Adapter for the filter and it works if I haven't made any new additions to the adapter
When I add a new item to Listview, the search stops completely until I restart the program after adding, modifying or deleting it
full code
adapter class
Do you want to achieve the result like following GIF?
If you want to add the item to the listview, based on your adapter, you should item in the adapter like following code.
public class TableItemAdapter : BaseAdapter<TableItem>, IFilterable
{
public List<TableItem> _originalData;
public List<TableItem> _items;
private readonly Activity _context;
public TableItemAdapter(Activity activity, IEnumerable<TableItem> tableitems)
{
_items = tableitems.ToList();
_context = activity;
Filter = new TableItemFilter(this);
}
//Add data to the `_items`, listview will be updated, if add data in the activity,
//there are two different lists, so listview will not update.
public void AddData(TableItem tableItem)
{
_items.Add(tableItem);
NotifyDataSetChanged();
}
public override TableItem this[int position]
{
get { return _items[position]; }
}
public Filter Filter { get; private set; }
public override int Count
{
get { return _items.Count; }
}
public override long GetItemId(int position)
{
return position;
}
public override View GetView(int position, View convertView, ViewGroup parent)
{
var item = _items[position];
View view = convertView;
if (view == null) // no view to re-use, create new
view = convertView ?? _context.LayoutInflater.Inflate(Resource.Layout.TableItem, null);
//view = _context.LayoutInflater.Inflate(Resource.Layout.TableItem, null);
view.FindViewById<TextView>(Resource.Id.Text1).Text = item.Heading;
view.FindViewById<TextView>(Resource.Id.Text2).Text = item.SubHeading;
return view;
}
public override void NotifyDataSetChanged()
{
// this.NotifyDataSetChanged();
base.NotifyDataSetChanged();
}
}
public class TableItemFilter :Filter
{
private readonly TableItemAdapter _adapter;
public TableItemFilter(TableItemAdapter adapter)
{
_adapter = adapter;
}
protected override FilterResults PerformFiltering(ICharSequence constraint)
{
var returnObj = new FilterResults();
var results = new List<TableItem>();
if (_adapter._originalData == null)
_adapter._originalData = _adapter._items;
if (constraint == null) return returnObj;
if (_adapter._originalData != null && _adapter._originalData.Any())
{
results.AddRange(
_adapter._originalData.Where(
item => item.SubHeading.ToLower().Contains(constraint.ToString()) | item.Heading.ToLower().Contains(constraint.ToString())));
}
returnObj.Values = FromArray(results.Select(r => r.ToJavaObject()).ToArray());
returnObj.Count = results.Count;
constraint.Dispose();
return returnObj;
}
protected override void PublishResults(ICharSequence constraint, FilterResults results)
{
using (var values = results.Values)
_adapter._items = values.ToArray<Java.Lang.Object>().Select(r => r.ToNetObject<TableItem>()).ToList();
_adapter.NotifyDataSetChanged();
// Don't do this and see GREF counts rising
constraint.Dispose();
results.Dispose();
}
}
public class JavaHolder : Java.Lang.Object
{
public readonly object Instance;
public JavaHolder(object instance)
{
Instance = instance;
}
}
public static class ObjectExtensions
{
public static TObject ToNetObject<TObject>(this Java.Lang.Object value)
{
if (value == null)
return default(TObject);
if (!(value is JavaHolder))
throw new InvalidOperationException("Unable to convert to .NET object. Only Java.Lang.Object created with .ToJavaObject() can be converted.");
TObject returnVal;
try { returnVal = (TObject)((JavaHolder)value).Instance; }
finally { value.Dispose(); }
return returnVal;
}
public static Java.Lang.Object ToJavaObject<TObject>(this TObject value)
{
if (Equals(value, default(TObject)) && !typeof(TObject).IsValueType)
return null;
var holder = new JavaHolder(value);
return holder;
}
}
}
Then in the activity, you add the data by adapter.
private void Button1_Click(object sender, System.EventArgs e)
{
tableItemAdapter.AddData(new TableItem() { Heading = "test1222", SubHeading = "sub Test" });
}
Here is my demo, you can download it.
https://github.com/851265601/Xamarin.Android_ListviewSelect/blob/master/XAListViewSearchDemo.zip

Avoid refreshing of content in SplitLayout

I have a splitlayout in my vaadin application in which in the first column I should show different pages added through the addToPrimary method, while in the second column I should have a page which contains an IFrame with a videoconference. Now the problem is that when I change route in the first column, even the second is updated and this refreshes the IFrame. The implementation of the showRouterLayoyutContent is the following:
#Override
public void showRouterLayoutContent(HasElement content) {
if (this.accessControl.isAccessGranted(UI.getCurrent(), ((ContentView) content).getName()) && ((ContentView) content).getName().equals("contattaView") ) {
setLayoutCall((com.vaadin.flow.component.Component) content);
}
else if (this.accessControl.isAccessGranted(UI.getCurrent(), ((ContentView) content).getName())) {
setLayoutContent((com.vaadin.flow.component.Component) content);
}
}
And the two methods setLayoutCall and setLayoutContent are the following:
private void setLayoutContent(com.vaadin.flow.component.Component content) {
split.addToPrimary(content);
}
private void setLayoutCall(com.vaadin.flow.component.Component content) {
split.addToSecondary(content);
split.setThemeName("visible-split");
}
How can I avoid to refresh the entire content when I update the first column of the split layout through navigation?
UPDATE: I'm showing also a very simple code on which I'm testing. The following class is the main layout:
private SplitLayout split = new SplitLayout();
private HorizontalLayout hl = new HorizontalLayout();
private Div firstDiv = new Div();
private Div secondDiv = new Div();
public MainView() {
Button button = new Button("Click me",
event -> Notification.show("Clicked!"));
final VerticalLayout menuBar = new VerticalLayout();
menuBar.add(new RouterLink("first view", FirstView.class));
menuBar.add(new RouterLink("second view", SecondView.class));
menuBar.setAlignItems(Alignment.CENTER);
add(menuBar);
//split.addToPrimary(firstDiv);
//split.addToSecondary(secondDiv);
//firstDiv.setId("first");
//secondDiv.setId("second");
//hl.add(firstDiv,secondDiv);
add(split);
//add(hl);
}
#Override
public void showRouterLayoutContent(HasElement element) {
if(element!=null && element.getClass().getName().contains("FirstView")) {
split.addToPrimary((Component) element);
//firstDiv.removeAll();
//firstDiv.add((Component) element);
//firstDiv.removeAll();
//firstDiv.getElement().appendChild(new Element[]{element.getElement()});
}
else if(element!=null && element.getClass().getName().contains("SecondView") ) {
secondDiv.removeAll();
secondDiv.add((Component) element);
split.addToSecondary((Component) element);
//split.addToSecondary(element.getElement().getComponent().get());
}
}
While these are the two views added to the split:
#Route(value="v1",layout=MainView.class)
public class FirstView extends VerticalLayout implements RouterLayout {
public FirstView() {
add(new Label("First View"));
}
}
#Route(value = "v2",layout=MainView.class)
public class SecondView extends VerticalLayout implements RouterLayout {
public SecondView() {
IFrame frame = new IFrame();
frame.setSrc("https://www.youtube.com/watch?v=LoigVtPCYPk&list=RDLoigVtPCYPk&start_radio=1");
add(frame);
}
}
Your comment does indeed seem to be the issue.
I recommend creating a Div wrapper for the primary content, and instead changing the content of that.
private final Div wrapper;
public MyLayout() {
wrapper = new Div();
wrapper.setSizeFull();
split.addToPrimary(wrapper);
}
private void setLayoutContent(com.vaadin.flow.component.Component content) {
wrapper.removeAll();
wrapper.add(content);
}
You might also want to do the same for the secondary. In addition, to prevent any components from being automatically removed when navigating, you can override removeRouterLayoutContent as well (available in Vaadin 14)
#Override
public void removeRouterLayoutContent(HasElement oldContent) {
// Do nothing, we remove manually in showRouterLayoutContent
}
Edit
If you can't override removeRouterLayoutContent, you can try creating your own instance of the HasElement to add. This is a bit of a hack, but might be the simplest solution.
public void showRouterLayoutContent(HasElement content) {
if (content.getClass().getSimpleName().contains("TestView")) {
// Creating a new instance should stop it from being auto removed
content = new TestView();
firstDiv.add((Component) content);
}
...
}

button inside column for each row in tableview

In my TableView I have column with button for each row for update so I need when click the button to take all the values from the row to a new fxml window
This is my contractor class:
public class constractor {
private String co_id;
private String co_name;
private String co_address;
private String co_create_date;
private String co_description;
private String co_mobile;
private String co_type_compile;
private String co_status;
private String co_type_model;
private Button button;
public constractor(String co_id, String co_name, String co_type_compile, String co_description, String co_create_date, String co_status, String co_address, String co_mobile, String co_type_model, String button) {
this.co_id = co_id;
this.co_name = co_name;
this.co_type_compile = co_type_compile;
this.co_description = co_description;
this.co_create_date = co_create_date;
this.co_status = co_status;
this.co_address = co_address;
this.co_mobile = co_mobile;
this.co_type_model = co_type_model;
this.button = new Button("edit");
}
public String getCo_id() {
return co_id;
}
public void setCo_id(String co_id) {
this.co_id = co_id;
}
public String getCo_name() {
return co_name;
}
public void setCo_name(String co_name) {
this.co_name = co_name;
}
public String getCo_address() {
return co_address;
}
public void setCo_address(String co_address) {
this.co_address = co_address;
}
public String getCo_create_date() {
return co_create_date;
}
public void setCo_create_date(String co_create_date) {
this.co_create_date = co_create_date;
}
public String getCo_description() {
return co_description;
}
public void setCo_description(String co_description) {
this.co_description = co_description;
}
public String getCo_mobile() {
return co_mobile;
}
public void setCo_mobile(String co_mobile) {
this.co_mobile = co_mobile;
}
public String getCo_type_compile() {
return co_type_compile;
}
public void setCo_type_compile(String co_type_compile) {
this.co_type_compile = co_type_compile;
}
public String getCo_status() {
return co_status;
}
public void setCo_status(String co_status) {
this.co_status = co_status;
}
public String getCo_type_model() {
return co_type_model;
}
public void setCo_type_model(String co_type_model) {
this.co_type_model = co_type_model;
}
public Button getButton() {
return button;
}
public void setButton(Button button) {
this.button = button;
}
}
This is my class for table:
public class MainscreenController implements Initializable {
#FXML
private TableView<constractor> co_tableview;
#FXML
private TableColumn<constractor, String> col_id;
#FXML
private TableColumn<constractor, String> col_name;
#FXML
private TableColumn<constractor, String> col_compaile_type;
#FXML
private TableColumn<constractor, String> col_description;
#FXML
private TableColumn<constractor, String> col_ceartedat;
#FXML
public TableColumn<constractor, String> col_status;
#FXML
private TableColumn<constractor, String> col_mobile;
#FXML
private TableColumn<constractor, String> col_type_model;
#FXML
private TextField search;
#FXML
private TableColumn<constractor, Button> col_button;
int indexorder = -1;
ObservableList<constractor> orderdata = FXCollections.observableArrayList();
#FXML
public void ordertables() {
Connection con = DB.getConnection();
orderdata.clear();
try {
try (ResultSet rs = con.createStatement().executeQuery("select * from mr_order")) {
while (rs.next()) {
orderdata.add(new constractor(
rs.getString("co_id"),
rs.getString("co_name"),
rs.getString("co_type_model"),
rs.getString("co_description"),
rs.getString("co_create_date"),
rs.getString("co_status"),
rs.getString("co_mobile"),
rs.getString("co_address"),
rs.getString("co_type_compile"),
rs.getString("co_user_id")
));
}
countneworder();
}
} catch (SQLException ex) {
Logger.getLogger(MainscreenController.class.getName()).log(Level.SEVERE, null, ex);
}
}
public int tablesandsearchorder() {
////tableview Itemsinserting
col_id.setCellValueFactory(new PropertyValueFactory<>("co_id"));
col_name.setCellValueFactory(new PropertyValueFactory<>("co_name"));
col_compaile_type.setCellValueFactory(new PropertyValueFactory<>
("co_type_compile"));
col_description.setCellValueFactory(new PropertyValueFactory<>
("co_description"));
col_ceartedat.setCellValueFactory(new PropertyValueFactory<>
("co_create_date"));
col_status.setCellValueFactory(new PropertyValueFactory<>("co_status"));
col_mobile.setCellValueFactory(new PropertyValueFactory<>("co_mobile"));
col_type_model.setCellValueFactory(new PropertyValueFactory<>
("co_type_model"));
col_button.setCellValueFactory(new PropertyValueFactory<>("button"));
co_tableview.setItems(orderdata);
co_tableview.getItems().setAll(orderdata);
co_tableview.itemsProperty().addListener((observable, oldItems, newItems)
-> {
countorder.textProperty().bind(
Bindings.size(newItems).asString());
});
// 2. Set the filter Predicate whenever the filter changes.
search.textProperty().addListener((ObservableValue<? extends String> observable, String oldValue, String newValue) -> {
filteredData.setPredicate(constractor -> {
// If filter text is empty, display all persons.
if (newValue == null || newValue.isEmpty()) {
return true;
}
// Compare first name and last name of every person with filter text.
String lowerCaseFilter = newValue.toLowerCase();
if
(constractor.getCo_name().toLowerCase().contains(lowerCaseFilter)) {
return true; // Filter matches first name.
} else if (constractor.getCo_id().toLowerCase().contains(lowerCaseFilter)) {
return true; // Filter matches last name.
} else if
(constractor.getCo_description().toLowerCase().contains(lowerCaseFilter)) {
return true; // Filter matches last name.
}
return false; // Does not match.
});
});
// 3. Wrap the FilteredList in a SortedList.
SortedList<constractor> sortedData = new SortedList<>(filteredData);
// 4. Bind the SortedList comparator to the TableView comparator.
sortedData.comparatorProperty().bind(co_tableview.comparatorProperty());
// 5. Add sorted (and filtered) data to the table.
co_tableview.setItems(sortedData);
return 0;
}
#FXML
public void openinsert() {
try {
//in this fxml i create the new order and also i need for update the status the order from this fxml when i click the button inside the tableview
FXMLLoader fxmlLoader = new FXMLLoader();
fxmlLoader.setLocation(getClass().getResource("createorder.fxml"));
Scene scene = new Scene(fxmlLoader.load());
Stage stage = new Stage();
stage.setTitle("neworder");
stage.setScene(scene);
stage.setFullScreen(false);
stage.setResizable(false);
stage.setMinHeight(400);
stage.setMinWidth(600);
stage.show();
} catch (IOException e) {
Logger logger = Logger.getLogger(getClass().getName());
logger.log(Level.SEVERE, "Failed to create new Window.", e);
}
}
It's usually recommended not mixing the view code (Button) with the model code (constractor). Instead you should use a custom TableCell class for the column.
Assuming you know how to pass the data (otherwise take a look here: Passing Parameters JavaFX FXML), all required info should be available via the constractor instance which you should pass to the new scene.
MainscreenController
#FXML
private TableColumn<constractor, Void> col_button;
...
private void editConstractor(constractor constractor) {
// TODO: implement
}
#FXML
private void initialize() {
col_button.setCellFactory(col -> new TableCell<constractor, Void>() {
private final Button button;
{
button = new Button("edit");
button.setOnAction(evt -> {
constractor item = getTableRow().getItem();
editConstractor(item);
});
}
#Override
protected void updateItem(Void item, boolean empty) {
super.updateItem(item, empty);
setGraphic(empty ? null : button);
}
});
}
You also need to remove the cellValueFactory for the button column.
Note:
Sticking to the java naming conventions would make the code easier to read. (Type names should start with an uppercase letter and identifiers should use camelCase instead of underscores assuming they're not for a static final field.)
constractor is most likely misspelled. Did you mean contractor? I recommend using the renaming functionality of your IDE to fix this typo...
(In my code I used the same spelling for the editConstractor method.)

Vaadin setting TextFIeld value in a Panel class

I have a problem in setting Textfield value in a class that extended Panel.
Heres my code.
package com.example.examplejpa;
import com.vaadin.ui.ComboBox;
import com.vaadin.ui.FormLayout;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Panel;
import com.vaadin.ui.TextField;
public class PersonnalInfoPanel extends Panel
{
/**
*
*/
private static final long serialVersionUID = 680441095924886309L;
private TextField claimantName;
private TextField insuredName;
private TextField dateofbirth;
private TextField age;
private TextField dateFrom;
private TextField dateTo;
private TextField noDays;
private ComboBox cause;
private SearchButton searchBtn = new SearchButton();
public PersonnalInfoPanel ()
{
setCaption("PERSONAL DATA INFO");
setWidth("500px");
FormLayout form = new FormLayout();
form.setSpacing(true);
form.setMargin(true);
form.addComponent(searchBtn);
claimantName = new TextField();
claimantName.setCaption("Claimant Name");
claimantName.setWidth("70%");
form.addComponent(claimantName);
insuredName = new TextField();
insuredName.setCaption("Insured Name");
insuredName.setWidth("70%");
form.addComponent(insuredName);
HorizontalLayout dateAge = new HorizontalLayout();
dateAge.setSpacing(true);
dateAge.setWidth("70%");
dateofbirth = new TextField();
dateofbirth.setCaption("Date of Birth");
dateofbirth.setWidth("100%");
dateAge.addComponent(dateofbirth);
age = new TextField();
age.setCaption("Age");
age.setWidth("100%");
dateAge.addComponent(age);
form.addComponent(dateAge);
HorizontalLayout dateRange = new HorizontalLayout();
dateRange.setSpacing(true);
dateRange.setWidth("70%");
dateFrom = new TextField();
dateFrom.setCaption("Date From");
dateFrom.setWidth("100%");
dateRange.addComponent(dateFrom);
dateTo = new TextField();
dateTo.setCaption("Date To");
dateTo.setWidth("100%");
dateRange.addComponent(dateTo);
form.addComponent(dateRange);
noDays = new TextField();
noDays.setCaption("No. of Days");
noDays.setWidth("70%");
form.addComponent(noDays);
cause = new ComboBox();
cause.setCaption("Cause");
cause.setWidth("70%");
form.addComponent(cause);
setContent(form);
}
public void setInsuredName (String newInsureName) { this.insuredName.setValue(newInsureName); }
public void setClaimantName (String newClaimantName) { this.claimantName.setValue("awd"); System.out.println(newClaimantName); }
public void setDateofbirth (String newDateofbirth) { this.dateofbirth.setValue(newDateofbirth); }
public void setAge (String newAge) { this.age.setValue(newAge); }
public void setDateFrom (String newDateFrom) { this.dateFrom.setValue(newDateFrom); }
public void setDateTo (String newDateTo) { this.dateTo.setValue(newDateTo); }
public void setNoDay (String newNoDay) { this.noDays.setValue(newNoDay); }
public TextField getClaimantName () { return this.claimantName; }
}
But when I access its setter method to set value for specific Component, it does nothing, still the value is empty..
I finally got answer to this question..
But my technique is I made my main class has an static method which calls the panels getter and setter methods.. thats how I solve my problem.. but it is a appropriate to do it ?

How to change the main view of a Vaadin 7 application?

I want to write a Vaadin 7 application (see MyVaadinUI below), which asks the user to enter user name and password.
If they are correct, another view (see MainUI below) should appear and take the entire area (replace the login view).
I tried to implement this transition in the method MyVaadinUI.goToMainWindow, but I get the error
java.lang.RuntimeException: Component must be attached to a session when getConnectorId() is called for the first time
at com.vaadin.server.AbstractClientConnector.getConnectorId(AbstractClientConnector.java:417)
at com.vaadin.server.communication.ConnectorHierarchyWriter.write(ConnectorHierarchyWriter.java:67)
at com.vaadin.server.communication.UidlWriter.write(UidlWriter.java:143)
at com.vaadin.server.communication.UidlRequestHandler.writeUidl(UidlRequestHandler.java:149)
at com.vaadin.server.communication.UidlRequestHandler.synchronizedHandleRequest(UidlRequestHandler.java:97)
at com.vaadin.server.SynchronizedRequestHandler.handleRequest(SynchronizedRequestHandler.java:37)
at com.vaadin.server.VaadinService.handleRequest(VaadinService.java:1371)
at com.vaadin.server.VaadinServlet.service(VaadinServlet.java:238)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:848)
when I run the application and press the button.
How can I fix it?
#Theme("mytheme")
#SuppressWarnings("serial")
public class MyVaadinUI extends UI
{
private TextField userNameTextField;
private PasswordField passwordTextField;
#WebServlet(value = "/*", asyncSupported = true)
#VaadinServletConfiguration(productionMode = false, ui = MyVaadinUI.class, widgetset = "ru.mycompany.vaadin.demo.AppWidgetSet")
public static class Servlet extends VaadinServlet {
}
#Override
protected void init(VaadinRequest request) {
final VerticalLayout layout = new VerticalLayout();
layout.setMargin(true);
setContent(layout);
addUserNameTextField(layout);
addPasswordTextField(layout);
addButton(layout, request);
}
private void addPasswordTextField(Layout aLayout) {
passwordTextField = new PasswordField("Пароль:");
aLayout.addComponent(passwordTextField);
}
private void addUserNameTextField(final Layout aLayout) {
userNameTextField = new TextField("Пользователь:");
aLayout.addComponent(userNameTextField);
}
private void addButton(final Layout aParent, final VaadinRequest request) {
final Button button = new Button("Войти");
button.addClickListener(new Button.ClickListener() {
public void buttonClick(Button.ClickEvent event) {
final boolean credentialsCorrect = checkCredentials();
if (credentialsCorrect) {
goToMainWindow(request);
} else {
[...]
}
}
});
aParent.addComponent(button);
}
private void goToMainWindow(final VaadinRequest aRequest) {
final MainUI mainUI = new MainUI();
mainUI.init(aRequest);
setContent(mainUI);
}
}
#Theme("mytheme")
#SuppressWarnings("serial")
public class MainUI extends UI {
#Override
protected void init(final VaadinRequest vaadinRequest) {
final HorizontalSplitPanel splitPanel = new HorizontalSplitPanel();
setContent(splitPanel);
splitPanel.setSizeFull();
splitPanel.setSplitPosition(200, Unit.PIXELS);
final String[] tabLabels = new String[] {
"Tree item 1",
"Tree item 2"};
final Tree tree = new Tree();
for (int i=0; i < tabLabels.length; i++)
{
addTreeItem(tree, tabLabels[i]);
}
splitPanel.setFirstComponent(tree);
splitPanel.setSecondComponent(new Label("Test"));
}
private void addTreeItem(final Tree aTree, final String aLabel) {
aTree.addItem(aLabel);
}
}
On the Vaadin forum someone suggested to use the navigator, which solved my problem.
I'd rather think that MainUI should extend HorizontalSplitPanel, not UI. It is strange concept to me to insert one UI into another.
You can use #SpringUI for the main class which extends UI:
#SpringUI
#Theme("mytheme")
#Widgetset("com.MyAppWidgetset")
#PreserveOnRefresh
public class MainUI extends UI {
private static final long serialVersionUID = -8247521108438815011L;
private static Locale locale = VaadinSession.getCurrent().getLocale();
#Autowired
private ToolBoxMessageSource messageSource;
#Autowired
private SpringViewProvider springViewProvider;
public MainUI() {
}
//Initializes navigator with SpringViewProvider and add all existing
//and ui specific assigned views to navigator.
#Override
protected void init(VaadinRequest vaadinRequest) {
Navigator navigator = new Navigator(this, this);
// Adding springViewProvider for spring autowiring
navigator.addProvider(springViewProvider);
// Adding all views for navigation
navigator.addView(LoginView.NAME, LoginView.class);
navigator.addView(MainView.NAME, MainView.class);
navigator.addView(MailToolView.NAME, MailToolView.class);
navigator.addView(AdminView.NAME, AdminView.class);
navigator.addView(EditRecipientView.NAME, EditRecipientView.class);
navigator.addView(EditRecipientsView.NAME, EditRecipientsView.class);
navigator.addView(ServerView.NAME, ServerView.class);
navigator.addView(TestJobView.NAME, TestJobView.class);
navigator.addView("", new LoginView());
navigator.navigateTo(LoginView.NAME);
navigator.setErrorView(LoginView.class);
// security: if user changes view check if the user has the required rights
navigator.addViewChangeListener(new ViewChangeListener() {
private static final long serialVersionUID = 7330051193056583546L;
#Override
public boolean beforeViewChange(ViewChangeEvent event) {
Toolbox toolbox = getSession().getAttribute(Toolbox.class);
if (TbRightManagement.checkAccess(event.getNewView().getClass(), toolbox)) {
return true;
} else {
if (toolbox != null) {
TBNotification.show(messageSource.getMessage("access.denied.title", locale),
messageSource.getMessage("access.denied.no_permissions.msg", locale),
Type.ERROR_MESSAGE);
navigator.navigateTo(MainView.NAME);
return false;
} else {
TBNotification.show(messageSource.getMessage("access.denied.title", locale),
messageSource.getMessage("access.denied.not_loggedin.msg", locale),
Type.ERROR_MESSAGE);
navigator.navigateTo(LoginView.NAME);
return false;
}
}
}
#Override
public void afterViewChange(ViewChangeEvent event) {}
});
}
}
And for the other views, as an example EditRecipientsView should be a #SpringView which extends a Vaadin Designer and implements a Vaadin View.
#SpringView(name = EditRecipientsView.NAME)
#Theme("mytheme")
#TbRight(loggedIn = true, mailTool = true)
public class EditRecipientsView extends RecipientsDesign implements View {
private static final long serialVersionUID = 1L;
public static final String NAME = "editRecipients";
private static Locale locale = VaadinSession.getCurrent().getLocale();
private BeanItemContainer<Recipient> recipientContainer;
private Uploader uploader;
#Autowired
private ToolBoxMessageSource messageSource;
public EditRecipientsView() {
super();
}
//Initializes the ui components of the recipient view.
#PostConstruct
public void init() {
btn_addRecipient.addClickListener(e -> { MainUI.getCurrent().getNavigator().navigateTo(EditRecipientView.NAME);});
}
//Handling data when entering this view.
#Override
public void enter(ViewChangeEvent event) {
if (getSession().getAttribute(UIMailing.class) != null) {
List<Recipient> recipientList = getSession().getAttribute(UIMailing.class).getRecipients();
if (recipientList != null) {
recipientContainer.removeAllItems();
} else {
recipientList = new ArrayList<Recipient>();
}
recipientContainer.addAll(recipientList);
recipient_table.sort(new Object[] {"foreName", "lastName"}, new boolean[] {true, true});
}
}
}

Resources