codenameone reference components from another function - codenameone

I have created a register form (not using the designer).
On the form I have created numerous text fields as well as a button with ...
Button btnRegister = new Button();
btnRegister.setName("btnRegister");
btnRegister.setText("Register");
btnRegister.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
frmRegister_btnRegister(f);
}
});
f.addComponent(btnRegister);
My question is how do I reference the textfields in the function being called from the button action listener. Specifically I am trying to set up arguments to use for a network call using addArgument. When I used the designer I used find(ComponentName) but that is not available anymore.
private void frmRegister_btnRegister(Form f) {
// register new user
ConnectionRequest r = new ConnectionRequest();
r.setUrl(sUrlWebSvc);
r.setPost(true);
r.addArgument("Rest", "1"); // restaurant code
r.addArgument("Req", "Register"); // R = register
//r.addArgument("first_name", findTxtUsertName(c).getText());
// show spinning dialog while connecting
InfiniteProgress prog = new InfiniteProgress();
Dialog dlg = prog.showInifiniteBlocking();
r.setDisposeOnCompletion(dlg);
NetworkManager.getInstance().addToQueueAndWait(r);
//System.out.println(r.getResponseData());
}

Assuming its defined just above this line:
Button btnRegister = new Button();
As:
TextField txt =....
Just change it to:
final TextField txt =....
And then you can pass it (or its getText() string value) to:
btnRegister.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
frmRegister_btnRegister(f, txt);
}
});
Naturally you will need to update the signature of frmRegister_btnRegister to accept a text field or a string.

Related

SpanButton client property throws NullPointerException

I am trying to get the client property on a SpanButton when clicked. It is throwing a NullPointerException.
I tested the same code with a regular button and it works just fine. I believe there could be a bug there.
Here is how you can recreate this issue from a barebone project:
Form hi = new Form("Hi World");
Button button = new Button("Button");
button.putClientProperty("id", 100);
SpanButton spanButton = new SpanButton("SpanButton");
spanButton.putClientProperty("id", 200);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
int id = (int) evt.getComponent().getClientProperty("id");
System.out.println("Standard Button action listener: id = " + id);
}
});
spanButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
int id = (int) evt.getComponent().getClientProperty("id");
System.out.println("Span button action listener: id = " + id);
}
});
hi.addComponent(button);
hi.addComponent(spanButton);
hi.show();
If you click on the button, the output is printed correctly:
Standard Button action listener: id = 100
If you click on the SpanButton, a NullPointerException is thrown. Upon investigation, I found out that the SpanButton getClientProperty("id") is returning null.
Note: I need to use the SpanButton because of its variable size support.
Instead of getComponent() use the aptly named getActualComponent().
The JavaDocs explain why:
Identical to ActionEvent#getComponent() except for the fact that a lead component will be returned if such a lead component is available.
This is important for components such as MultiButton which will return the underlying button instead.

Codename One Back Command on left and Menu on Right

i am trying to make an app in Codename one where i want to create a handburger menu on the right side at the top of the screen and a back button on the left side, but cannot get it to work I know it can be done where you have a handburger menu on the left side and a button on the right side. I made a picture of how I want it to look like. The back button is added in paint and not through the code.
Picture of app example
below is the code that I have used to get the menu on the right side.
public class MainForm {
public static Form mainForm;
Command cmd_back, cmd_AboutTheApp;
private enum SideMenuMode {
SIDE, RIGHT_SIDE {
public String getCommandHint() {
return SideMenuBar.COMMAND_PLACEMENT_VALUE_RIGHT;
}
};
public String getCommandHint() {
return null;
}
public void updateCommand(Command c) {
String h = getCommandHint();
if(h == null) {
return;
}
c.putClientProperty(SideMenuBar.COMMAND_PLACEMENT_KEY, h);
}
};
SideMenuMode mode = SideMenuMode.RIGHT_SIDE;
public void init(Object context) {
theme = UIManager.initFirstTheme("/theme");
UIManager.getInstance().setThemeProps(theme.getTheme theme.getThemeResourceNames()[0]));
UIManager.getInstance().getLookAndFeel().setMenuBarClass(SideMenuBar.class);
Display.getInstance().setCommandBehavior(Display.COMMAND_BEHAVIOR_SIDE_NAVIGATION);
}
public void start() {
if(mainForm != null){
mainForm.show();
return;
}
mainForm = new Form();
mainForm.setTitleComponent(title);
mainForm.setLayout(new BorderLayout());
addCommands(mainForm);
}
private void addCommands(Form f){
cmd_Back = new Command("Back");
final Button btn_Back = new Button("Back");
cmd_Back.putClientProperty("TitleCommand", btn_Back);
btn_BackButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
//do some thing
}
});
cmd_AboutTheApp = new Command("About the app");
final Button btn_AboutTheApp = new Button("About the app");
cmd_AboutTheApp.putClientProperty("SideComponent", btn_AboutTheApp);
btn_AboutTheApp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
//do some thing
}
});
mode.updateCommand(cmd_Back);
f.addCommand(cmd_Back);
mode.updateCommand(cmd_AboutTheApp);
f.addCommand(cmd_AboutTheApp);
}
}
if I move the back button so that it is added after AboutTheApp button then the back button is displayed on the right side of the screen but also to the right of the menu, which is also on the right side. I've tried a lot of different ways but none seems to be working
We supported a right side menu bar in the SideMenuBar but not in the Toolbar API. We support placing components/commands in the left/right side of the title area in the Toolbar API but not in the SideMenuBar.
I guess the solution is to add support for the right menu bar into the Toolbar API but I'm not sure what the complexities are for such a change.
I suggest filing an RFE in the issue tracker asking for this but it probably won't be soon as we are closing the features for 3.3 right now.
I have an app that does this. Search Google Play (or App Store) for "Torquepower Diesel Cummins Engine" app.
in the theme Constants I set my own rightSideMenuImage and rightSideMenuPressImage, but the default hamburger menu may be OK for you.
On the beforeXXXX of each form I do something like this:
super.beforePartNumberForm(f);
Toolbar tb = createToolbar(f);
createBackCommand(f, tb);
addHelpX(tb);
addViewCartX(tb);
addCallTorquepowerX(tb);
addReverseSwipe(f);
create the toolbar
Toolbar createToolbar(Form f) {
Toolbar tb = new Toolbar();
f.setToolBar(tb);
Label l = new Label();
l.setIcon(res.getImage("tpd_logoZZ.png"));
tb.setTitleComponent(l);
return tb;
}
create the back button
void createBackCommand(Form f, Toolbar tb) {
Command c = new Command("") {
#Override
public void actionPerformed(ActionEvent evt) {
back();
}
};
c.setIcon(res.getImage("black_left_arrow-512.png"));
c.setPressedIcon(res.getImage("grey_left_arrow-512.png"));
// MUST set this before adding to toolbar, else get null pointer
f.setBackCommand(c);
tb.addCommandToLeftBar(c);
}
add whatever commands are needed to the sidemenu
void addHelpX(Toolbar tb) {
Command c = new Command("Help") {
#Override
public void actionPerformed(ActionEvent evt) {
showForm("HelpForm", null);
}
};
c.putClientProperty(SideMenuBar.COMMAND_PLACEMENT_KEY, SideMenuBar.COMMAND_PLACEMENT_VALUE_RIGHT);
c.putClientProperty("SideComponent", new SideMenuItem(fetchResourceFile(), c.toString(), "very_basic_about.png"));
c.putClientProperty("Actionable", Boolean.TRUE);
tb.addCommandToSideMenu(c);
}
I use my own SideMenuItem which is:
public class SideMenuItem extends Button {
SideMenuItem() {
this("");
}
SideMenuItem(String s) {
super(s);
setUIID("SideMenuItem");
int h = Display.getInstance().convertToPixels(8, false);
setPreferredH(h);
}
SideMenuItem(Resources res, String s, String icon) {
super();
setIcon(res.getImage(icon));
setText(s);
setUIID("SideMenuItem");
int h = Display.getInstance().convertToPixels(8, false);
setPreferredH(h);
}
}

how to display a image on click of a button using LWUIT

I am trying to write a application using LWUIT where I want a image to be displayed on click of a button.
I have the following code. But I get an exception if the button is clicked twice.
Please help me display the image without giving any exception.
final Form f = new Form("Static TAF");
Button TrackMe = new Button("TrackMe");
Image TrackMeicon = null;
TrackMeicon = Image.createImage("/hello/follow.jpeg");
final Label TrackMeLabel = new Label(TrackMeicon);
TrackMe.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
System.out.println("Removing the previous Images");
f.addComponent(TrackMeLabel);
}
});
Please Help
When you are clicking the button for the first time, image is added to the form. When you are clicking for the second time, that image already exists in the form. So, it will throw "Component already exists" exception.
Your action listener should be
TrackMe.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae) {
System.out.println("Removing the previous Images");
f.removeComponent(TrackMeLabel);
f.addComponent(TrackMeLabel);
}
});
TrackMe.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae) {
System.out.println("Removing the previous Images");
final Label TrackMeLabel = new Label(TrackMeicon);
f.removeAll();
f.addComponent(TrackMeLabel);
}
});
If you want yo add only one image you can use this:
....
TrackMe.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae) {
if(!f.containes(TrackMeLabel))
f.addComponent(TrackMeLabel);
}
if you want some imges you need something like that:
....
TrackMe.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae) {
Image TrackMeicon = null;
TrackMeicon = Image.createImage("/hello/follow.jpeg");
Label TrackMeLabel = new Label(TrackMeicon);
f.addComponent(TrackMeLabel);
}

Custom Item Template Wizard button click doesn't fire?

I am following this exactly:
http://msdn.microsoft.com/en-us/library/ms185301.aspx
but can't get it to work. The form appears when I try and add my new item, but when I input text and click the button, nothing happens.
For posterity's sake here is my code:
The non-empty methods in the Wizard class which extends IWizard
public void RunStarted(object automationObject,
Dictionary<string, string> replacementsDictionary,
WizardRunKind runKind, object[] customParams)
{
try
{
// Display a form to the user. The form collects
// input for the custom message.
inputForm = new UserInputForm();
inputForm.ShowDialog();
customMessage = inputForm.get_CustomMessage();
// Add custom parameters.
replacementsDictionary.Add("$custommessage$",
customMessage);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
// This method is only called for item templates,
// not for project templates.
public bool ShouldAddProjectItem(string filePath)
{
return true;
}
The user input form code:
public partial class UserInputForm : Form
{
private string customMessage;
public UserInputForm()
{
InitializeComponent();
}
public string get_CustomMessage()
{
return customMessage;
}
private void button1_Click(object sender, EventArgs e)
{
customMessage = textBox1.Text;
this.Dispose();
}
}
And the button is indeed named button 1:
this.button1.Location = new System.Drawing.Point(200, 180);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(100, 40);
this.button1.TabIndex = 0;
this.button1.Text = "Click Me";
this.button1.UseVisualStyleBackColor = true;
So I don't have much experience with Windows Forms (do web apps), but I am following the directions on MSDN and it's pretty clear cut. Any suggestions? Can anyone else get this to work?
Okay I figured it out. I had to add the event handler in the form's constructor manually:
public UserInputForm()
{
InitializeComponent();
button1.Click += button1_Click;
}
Why this isn't in the documentation on MSDN boggles my mind.
If you use the WinForms designer mode to drag your button from the Toolbox, and then double-clicked the button in the designer view, it would have added the event handler and stubbed that Click method for you. Just FYI.

AWT repaint issues

I am trying to make some small additions to some old java code that does not support swing. I need to add a small dialog that contains a panel which has a checkbox and a couple text fields. When the user clicks on the checkbox I want to disable or enable the checkboxes. This part seems to work well but the text fields are not properly getting redrawn. When I click the checkbox the fields do not appear to become enabled but if I then click on the panel or the text field you see that they are enabled (the opposite is also true, when I un-check the checkbox the fields still look enabled until you try and click on them and they become ghosted and do not become selected). I use the setEnabled(boolean) to set the status of the fields. I have tried calling repaint and validate on both the fields and the panel after changing the status and this does not seem to work. I have also tried to have the fields request focus and this did not work. Anyone have any other ideas?
//The class that contains all of this is of type Window
//Declaration of the components
private Panel _inputPanel;
private TextField min , max;
//This method adds to two text fields
public void addMinMaxtextFields(String min, String max) {
TextField minField = new TextField(min);
TextField maxField = new TextField(max);
this.min = minField;
this.max = maxField;
this.min.setEnabled(false);
this.max.setEnabled(false);
_inputPanel.add(minField);
_inputPanel.add(maxField);
}
//listener for the checkbox
public void itemStateChanged(ItemEvent e) {
Component[] components = _inputPanel.getComponents();
min.setEnabled(!min.isEnabled());
min.setVisible(true);
min.validate();
min.repaint();
_inputPanel.validate();
_inputPanel.repaint();
this.pack();
this.setSize(this.getWidth(), this.getHeight());
this.validate();
this.repaint();
/* do nothing */
}
You will need to call update(Graphics g) on Panel after setEnabled(boolean) is called.
check :
http://download-llnw.oracle.com/javase/1.4.2/docs/api/java/awt/Container.html#update(java.awt.Graphics)
I tried following code (built from code you provided), Its working fine.
import java.awt.Checkbox;
import java.awt.Component;
import java.awt.Dialog;
import java.awt.Frame;
import java.awt.Panel;
import java.awt.TextField;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
public class CheckUI extends Dialog implements ItemListener {
// The class that contains all of this is of type Window
// Declaration of the components
private Panel _inputPanel;
private TextField min, max;
private Checkbox cb;
public CheckUI(Frame owner, boolean modal) {
super(owner, modal);
_inputPanel = new Panel();
this.add(_inputPanel);
addMinMaxtextFields("min", "max");
}
// This method adds to two text fields
public void addMinMaxtextFields(String min, String max) {
cb = new Checkbox();
cb.addItemListener(this);
TextField minField = new TextField(min);
TextField maxField = new TextField(max);
this.min = minField;
this.max = maxField;
this.min.setEnabled(false);
this.max.setEnabled(false);
_inputPanel.add(minField);
_inputPanel.add(maxField);
_inputPanel.add(cb);
}
// listener for the checkbox
public void itemStateChanged(ItemEvent e) {
Component[] components = _inputPanel.getComponents();
min.setEnabled(!min.isEnabled());
min.setVisible(true);
min.validate();
min.repaint();
_inputPanel.validate();
_inputPanel.repaint();
this.pack();
this.setSize(this.getWidth(), this.getHeight());
this.validate();
this.repaint();
/* do nothing */
}
/**
* #param args
*/
public static void main(String[] args) {
Frame parent = new Frame();
parent.setVisible(true);
parent.setExtendedState(Frame.MAXIMIZED_BOTH);
parent.pack();
CheckUI ui = new CheckUI(parent, true);
ui.pack();
ui.setVisible(true);
}
}

Resources