lwuit change UI language - internationalization

I use codenameone to develop my mobile application. In this application I implement some classes and codes manually for instance create all forms by hard coding not using codenameone designer for some reason.
By the way I wanted to navigate in forms like what codenameone use, so I use one variable from type of Form called it prevForm and when I want to open a form I set it to current form and then I show new form.
Ok, that is main scenario. In this application I wanna implement internationalization too, so I create my own hashtable (Farsi and English) for this application.
This is my problem:
How can I set or change language and apply it to forms that I opened?
Is my method for navigate between forms are good?
Here is my code:
public class BaseForm extends Form implements ActionListener {
public BaseForm(){
this.setLayout(new BoxLayout(BoxLayout.Y_AXIS));
}
Command exit, ok, back;
Form prevForm;
protected void initForm(){
}
protected void showForm(){
}
protected void showForm(final Form prevForm){
//String name = this.getName();
//if("Reminder".equals(name) || "3Transaction".equals(name))
{
this.prevForm = prevForm;
Form f = this;
back = new Command("Back");
//ok = new Command("Ok");
//delete = new Command("Delete");;
Button button = new Button("Button");
f.addCommand(back);
//f.addCommand(ok);
//f.addCommand(delete);
//f.addComponent(button);
f.addCommandListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if (ae.getCommand().equals(back)) {
//Do Exit command code
System.out.println("Back pressed");
prevForm.showBack();
} else if (ae.getCommand().equals(ok)) {
//Do Start command code
System.out.println("Ok pressed");
}
}
});
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
//Do button code
System.out.println("Action performed");
}
});
}
showForm();
}}
for open nested form I use this code:
LanguageUI lang = new LanguageUI();
lang.showForm(this);
change language [form]:
protected boolean onBtnSave() {
if(isRbFarsiSelected()){
UIManager.getInstance().setResourceBundle(new CommonSettings().getFarsi());
}
else {
UIManager.getInstance().setResourceBundle(new CommonSettings().getEnglish());
}
return false;
}

I also hard code my UI on lwuit, and i have a variable parentForm on every class so i can easily show previous form. For language change i know there is Localization in the resource editor that you can make use of. Below is how you can access it. I guess the trick is how to set the content of the L10N in the res file in code? On the other hand you can create your own helper classes that mirror the methods below.
Resources theme = Resources.open("/theme.res");
theme.getL10N(id, locale);
theme.getL10NResourceNames();
theme.isL10N(name);
theme.listL10NLocales(id)

Related

Windows Phone Back button and page instance creation

I need to recreate new page instance on every page load (also when user pressed Back button).
So I overrided OnBackKeyPress method:
protected override void OnBackKeyPress(CancelEventArgs e)
{
base.OnBackKeyPress(e);
if (NavigationService.CanGoBack) {
e.Cancel = true;
var j = NavigationService.RemoveBackEntry();
NavigationService.Navigate(j.Source);
NavigationService.RemoveBackEntry();
}
}
The problem is that I can't handle case when user press back button to close CustomMessageBox dialog. How can I check it? Or is there any way to force recreation of page instance when going back through history state?
Why do you need to recreate the page instance? If you are simply trying to re-read the data to be displayed, why not put the data loading logic into OnNavigatedTo()?
Assuming that is what you are actually trying to achieve, try something like this...
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
// don't do your data loading here. This will only be called on page creation.
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
LoadData();
base.OnNavigatedTo(e);
}
MyViewModel model;
async void LoadData()
{
model = new MyViewModel();
await model.LoadDataAsync();
}
}
If you also have specific logic that you need to run on first construction of the page vs. on a back key navigation, check the NavigationMode property of the NavigationEventArgs object that gets passed to OnNavigatedTo.
if(e.NavigationMode == NavigationMode.New)
{
//do what you need to do specifically for a new page instance
}
if (e.NavigationMode == NavigationMode.Back)
{
// do anything specific for back navigation here.
}
Ha, in the near thread, i have opposite question :)
What about MessageBox - it depends, which one are you using. It can be custom message box, for example. Anyway, try to check MessageBox.IsOpened (or alternative for your MessageBox) in your OnBackKeyPress().
Another solution is to use OnNavigatedTo() of the page you want to be new each time.
Third solution: in case you works with Mvvm Light, add some unique id in ViewModel getter, like
public MyViewModel MyViewModel
{
get
{
return ServiceLocator.Current.GetInstance<MyViewModel>((++Uid).ToString());
}
}
This would force to recreate new ViewModel each time, so you'd have different instance of VM, so you would have another data on the View.

Eclipse Plugin Development---PopupMenuCreation

I am developing a wizard using eclipse plugin development.
Requirement:
I have to create a context menu that needs to get populated as soon as the user right clicks on the source folder in java project. once the User performs the first step my handler needs to get the selected src folder in my wizard. My wizard contains a treeviewer where i need to get the selected src folder packaged.
My analysis:
i have my handler class that gets the selected packages
SampleHandler.java
public Object execute(ExecutionEvent event) throws ExecutionException {
shell = HandlerUtil.getActiveShell(event);
// Initializing workbench window object
IWorkbenchWindow window = (IWorkbenchWindow) HandlerUtil.getActiveWorkbenchWindow(event);
ISelection sel = HandlerUtil.getActiveMenuSelection(event);
final IStructuredSelection selection = (IStructuredSelection) sel;
Object firstElement = selection.getFirstElement();
if (firstElement instanceof IPackageFragment) {
// Get the selected fragment
IPackageFragment packageFragment = (IPackageFragment) firstElement;
modelPackage = packageFragment.getElementName();
boolean a =!ProjectResourceHelper.isEntityBasePackage(modelPackage);
if(a == true){
MessageDialog.openInformation(shell, "Warning", "Please click from entity base package");
Shell shell = HandlerUtil.getActiveShell(event);
GreenWizard wizard = new GreenWizard();
WizardDialog dialog = new WizardDialog( part.getSite().getShell(), wizard);
dialog.create();
dialog.open();
return null;
}
try{
window.run(true, true, new IRunnableWithProgress(){
#Override
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
monitor.beginTask("Layer codes are being generated...", 1);
// Invocation of generate layers method
monitor.worked(1);
// Done with operation completion.
monitor.done();
}
});
}
catch(InvocationTargetException ite){
MessageDialog.openError(shell, "Greenfield Code Generation Exception", ite.getMessage());
}
catch (InterruptedException ie) {
MessageDialog.openError(shell, "Greenfield Code Generation Exception", ie.getMessage());
}
}
I have my main wizard class that is called within this method.
GreenWizard wizard = new GreenWizard();
and my main wizard in return calls my wizard page where i need to get the selection performed on right click by the user.
My Wizardpageclass
public GenerateGreenfieldLayer(IWorkbench workbench,
IStructuredSelection selection) {
super("Greenfield");
setImageDescriptor(ResourceManager
.getImageDescriptor("\\icons\\greenfield-new-wiz.png"));
setTitle("GreenField Generate layer");
setDescription("Select specfic class to grenerate Layers");
}
/**
* Create contents of the wizard.
*
* #param parent
*/
#Override
public void createControl(Composite parent) {
Composite container = new Composite(parent, SWT.NULL);
setControl(container);
container.setLayout(new GridLayout(2, false));
final CheckboxTreeViewer treeViewer = new CheckboxTreeViewer(container,
SWT.BORDER);
tree = treeViewer.getTree();
tree.setToolTipText("Choose package");
GridData gd_tree = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1);
gd_tree.widthHint = 280;
gd_tree.heightHint = 140;
tree.setLayoutData(gd_tree);
treeViewer.setContentProvider(new GreenfieldTreeContentProvider());
treeViewer.setLabelProvider(new WorkbenchLabelProvider());
treeViewer.addSelectionChangedListener(new ISelectionChangedListener () {
public void selectionChanged(SelectionChangedEvent event) {
}
});
}
Can anyone please guide me how to get the selection from object method and pass as treeviewer initial input in my wizard page.
Please correct me if i am missing any steps as i am very new to this.
Thanks in advance
You should separate the code into the following pieces and dataflows:
Handler: get the selection and create the wizard and wizard dialog (as you do already)
Handler->Wizard: use the Wizard's constructor or a custom init(foo) method (which you call from the handler) to set the selected object (or whatever you want to pass as initial data) from the handler
Wizard->WizardPage: When creating the Wizard, instantiate the WizardPage(s) and pass the selection to the wizard pages. (If you need a more complex model which is shared between the Wizard and its pages consider creating an instantiating a simple value-holder class as your wizard model; i.e., a simple java class with your data and getters/setters. That object can then be shared across the pages if you pass it to every page's constructor)
WizardPage: create UI for wizard page, let user modify the model
WizardPage->Wizard: if you do not use the shared wizard model via a value-holder class, have a getXxx() method to let the wizard access the user's input from the page
Wizard: implement Wizard.performFinish() to do the work at the end of the wizard using getContainer().run() instead of having the window.run() call in your handler.

How to add DropListener to drop text in a draw2d Label

I am Trying to add a dropListener so I can Drop and text into a draw2d Label ,in GEf Editor , Can anyone help how Can I do that. An example will be great.
To respond to drop events on a GEF edit part viewer you have to install on the viewer itself an implementation of org.eclipse.jface.util.TransferDropTargetListener that understands transfers of type org.eclipse.swt.dnd.TextTransfer and that creates some kind of org.eclipse.gef.Request that can be handled by an org.eclipse.gef.EditPolicy installed on the target org.eclipse.gef.EditPart.
You have to understand that both the Request and the EditPolicy allow you to customize the drop behavior on a EditPart basis. As a consequence, I can show you an example that is actually fully functional, but feel free to customize it to your real needs.
First create the TransferDropTargetListener:
public class TextTransferDropTargetListener extends AbstractTransferDropTargetListener {
public TextTransferDropTargetListener(EditPartViewer viewer) {
super(viewer, TextTransfer.getInstance());
}
#Override
protected void handleDragOver() {
getCurrentEvent().feedback = DND.FEEDBACK_SCROLL | DND.FEEDBACK_EXPAND;
super.handleDragOver();
}
#Override
protected Request createTargetRequest() {
return new ChangeBoundsRequest(REQ_ADD);
}
#Override
protected void updateTargetRequest() {
ChangeBoundsRequest request = (ChangeBoundsRequest) getTargetRequest();
request.setEditParts(Collections.EMPTY_LIST);
request.setLocation(getDropLocation());
}
#Override
protected void handleDrop() {
super.handleDrop();
if (getCurrentEvent().detail != DND.DROP_NONE) {
getViewer().setSelection(StructuredSelection.EMPTY);
getViewer().getControl().setFocus();
}
}
#Override
protected Command getCommand() {
String text = (String) getCurrentEvent().data;
List<IEntityPart> editParts = new ArrayList<IEntityPart>();
//
// using the 'text' variable you have to create
// a new EditPart that would eventually replace the old one.
//
editParts.add(createNewLabelPart());
ChangeBoundsRequest request = (ChangeBoundsRequest) getTargetRequest();
request.setEditParts(editParts);
return super.getCommand();
}
}
then install the listener in the graphical viewer constructor using the following statement:
addDropTargetListener(new TextTransferDropTargetListener(this));
finally ensure that an EditPolicy that understands requests of type REQ_ADD (maybe you already added one that extends LayoutEditPolicy or ContainerEditPolicy) is installed on the target EditPart, which is usually done in the AbstractEditPart.createEditPolicies().
To better understand the chain of responsibilities, I suggest you to have a look at the super implementation of the TransferDropTargetListener.getCommand() method.

Change themes in Vaadin 7 via code

I am doing a project in Vaadin 7. In that I need to change the theme of a page.
In Vaadin 6, there is a function called 'setTheme()'. so that I can change the theme using that function wherever I want in my code.
But, In Vaadin 7, I couldn't find any like that.
I know there will be a way to do it.
And also how to apply changes on the UI when I change a theme?
Will it be changed automatically? (or)
ICEPush gonna help me?
In Vaadin 7 the method 'setTheme()' has been replaced with the new Annotation #Theme. The "on the fly theme change" is not possible in Vaadin 7.
There is a disucssion in this Vaadin Forum Thread about the on fly theme change in Vaadin 7. You should have a look on it.
setTheme functionality has been introduced in Vaadin 7.3.0: https://vaadin.com/wiki/-/wiki/Main/Changing+theme+on+the+fly
you can try this for Vaadin 7:
Create your own UIProvider
Register your UIProvider in root UI
Switch theme in UIProvider and trigger page reload
DynamicThemeUIProvider.java
public class DynamicThemeUIProvider extends UIProvider {
private String currentTheme = "reindeer";
#Override
public Class<? extends UI> getUIClass(UIClassSelectionEvent event) {
return DemoUI.class;
}
public void setTheme(String theme) {
currentTheme = theme;
}
public String getTheme(UICreateEvent event) {
return currentTheme;
}
}
DemoUI.java
public class DemoUI extends UI {
private DynamicThemeUIProvider provider;
#Override
protected void init(VaadinRequest request) {
provider = new DynamicThemeUIProvider();
getSession().addUIProvider(provider);
}
public DynamicThemeUIProvider getDynamicThemeUIProvider() {
return provider;
}
}
Then on a component which switches the theme:
#Override
public void valueChange(ValueChangeEvent event) {
DemoUI ui = (DemoUI) getUI();
DynamicThemeUIProvider uiProvider = ui.getDynamicThemeUIProvider();
if (uiProvider == null) {
return;
}
uiProvider.setTheme("reindeer");
try {
String value = (String) event.getProperty().getValue();
uiProvider.setTheme(value.toLowerCase());
} catch (Exception e) {
e.printStackTrace();
}
ui.getPage().getJavaScript().execute("document.location.reload(true)"); // page refresh
}
Since I used custom themes, I have made it pretty simple. I used a toggle button and executed the required piece of code every time.
JavaScript.getCurrent().execute("document.body.className = document.body.className.replace(\"theme1\",\"theme2\"); ");
JavaScript.getCurrent().execute("document.body.className = document.body.className.replace(\"theme2\",\"theme1\"); ");
My css file will be like this.
.theme1 .v-button {
/* some css attribute */
}
.theme2 .v-button {
/* some css attribute */
}
Believe me; the theme switch is very very fast since the browser itself do the trick to switch the theme rather than asking the Vaadin server to do the switch.
Regarding themes for charts:
simply have a switch somewhere inside a listener of either a ComboBox or an OptionGroup (for radio buttons) to make a the following ChartOptions static method call, e.g.:
ChartOptions.get().setTheme(new VaadinTheme())
then
ChartOptions.get().setTheme(new SkiesTheme())
etc.
there's also GridTheme(); GrayTheme() and HighChartsDefaultTheme(); you can even extend the base theme to create your own theme (look that up in the Book of Vaadin).
Since Vaadin 7.3 you can use UI#setTheme()
In Vaadin 7 and higher Versions we have an Annotation called #Theme(yourThemeName)
based on the Theme name which you give here it will redirect to that specific .scss Style.This annotation is called before the Init method is called.

How do I mask the current page behind a modal dialog box in vanilla GWT?

I've built a log-in composite that I am displaying in my application entry-point to the user. Upon entry of the username and password, I am sending the username and password to the server via a RemoteService and will receive back an object containing the ClientSession. If the ClientSession is a valid object (recognised username and password), I wish to display the main application panel otherwise I want to display the login dialog again (with an error message).
My question is, that during the async call to the server, how to I mask the screen so that the user cannot click anything whilst the Session is obtained from the server?
I know that the login should be fast, but the Session object contains a lot of Client Side cached values for the current user that is used to generate the main panel. This may take a fraction of a second or up to 5 seconds (I can't control the speed of the underlying infrastructure unfortunately) so I want to mask the screen until a timeout is reached then allow the user to try again.
I have done this exact operation before using GWT Ext, but vanilla GWT seems to have a lot less samples unfortunately.
Thanks
Chris
The GWT class PopupPanel has an optional "glass panel" that blocks interaction with the page underneath.
final PopupPanel popup = new PopupPanel(false, true); // Create a modal dialog box that will not auto-hide
popup.add(new Label("Please wait"));
popup.setGlassEnabled(true); // Enable the glass panel
popup.center(); // Center the popup and make it visible
You might want to check out GlassPanel from the GWT Incubator project. AFAICT it's not perfect, but should be of some help nevertheless ;)
You can also use a dialog box for this purpose.
Here is the code how to use it.
public class NTMaskAlert extends DialogBox {
private String displayText;
private String message;
private static NTMaskAlert alert;
Label lable;
private NTMaskAlert(String text) {
setText(text);
setWidget(new Image(GWT.getModuleBaseURL()
+ "/images/ajax-loader_1.gif"));
setGlassEnabled(true);
setAnimationEnabled(true);
super.show();
super.center();
WorkFlowSessionFactory.putValue(WorkFlowSesisonKey.MASKING_PANEL, this);
}
public static void mask(String text) {
if (text != null)
new NTMaskAlert(text);
else
new NTMaskAlert("Processing");
}
public static void unMask() {
NTMaskAlert alert = (NTMaskAlert) WorkFlowSessionFactory
.getValue(WorkFlowSesisonKey.MASKING_PANEL);
if (alert != null) {
alert.hide();
alert = null;
}
}
public void setDisplayText(String displayText) {
this.displayText = displayText;
alert.setText(displayText);
}
public String getDisplayText() {
return displayText;
}
public void setMessage(String message) {
this.message = message;
lable.setText(message);
}
public String getMessage() {
return message;
}
}
Use static mask and unmask method for operations.
This is my solution:
public class CustomPopupPanel extends PopupPanel {
private Label label = new Label();
public CustomPopupPanel() {
super(false, true); // Create a modal dialog box that will not auto-hide
super.setGlassEnabled(true); // Enable the glass panel
super.add(label); // Add the widget label into the panel
}
public CustomPopupPanel(String text) {
this();
this.mask(text);
}
public final void mask(String text) {
label.setText(text);
super.center(); // Center the popup and make it visible
}
public void unmask() {
super.hide(); // Hide the popup
}
}

Resources