How to detect key pressed event in LWUIT form? - java-me

I have written simple j2me program with LWUIT package.I have added one Form in my MIDLET class file. Suppose,user press a key then I want to show another Form.But I couldn't be able to capture key event in my LWUIT Form.
This is my code snippt
import javax.microedition.midlet.*;
import com.sun.lwuit.*;
import com.sun.lwuit.events.*;
public class MultipleForm extends MIDlet implements ActionListener{
private Form mFirstForm, mSecondForm;
public void startApp()
{
if (mFirstForm == null)
{
Display.init(this);
mFirstForm = new Form("First Form");
Button button = new Button("Switch");
button.addActionListener(this);
mFirstForm.addComponent(button);
mSecondForm = new Form("Second Form");
Button button2 = new Button("Switch");
button2.addActionListener(this);
mSecondForm.addComponent(button2);
mFirstForm.show();
}
}
protected void keyPressed(int key)
{
System.out.println("Key Pressed");
if(key==52)
{
Form current = Display.getInstance().getCurrent();
if (current == mFirstForm)
{
mSecondForm.show();
}
else if(current==mSecondForm)
{
mFirstForm.show();
}
}
}
public void pauseApp() {}
public void destroyApp(boolean unconditional) {}
}

To capture the event key in a LWUIT Form you need to use Form.addGameKeyListener(here the key, here actionListener)
The keys are mapped using Canvas like Canvas.FIRE for example.
Try to do that.

Related

TextField type to Show Button in javafx

I am trying Show a Button on TextField look like Windows 8 Metro theme in javafx.
If TextField is empty button is invisible otherwise button show.
In this stage i'm little close to success. i use this code to make it.
#FXML
private TextField tfMyName;//fx:id="tfMyName"
#FXML
private Button btnClear;//fx:id="btnClear"
#Override
public void initialize(URL url, ResourceBundle rb) {
clearTextFieldByButton(tfMyName, btnClear);
}
public void clearTextFieldByButton(TextField value, Button btn){
btn.setVisible(false);
value.setOnKeyTyped(new EventHandler<KeyEvent>(){
#Override
public void handle(KeyEvent event) {
if ((value.textProperty().get().length() < 0) || (value.textProperty().get().equals(""))) {
btn.setVisible(false);
} else if (value.textProperty().get().length() > -1 || (!value.textProperty().get().equals(""))) {
btn.setVisible(true);
}
}
});
btn.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
tfMyName.clear();
btn.setVisible(false);
tfMyName.requestFocus();
}
});
Using this code by default button is invisible but the button is only visible when i type more then one Characters.
But i need if anything input into the TextField to Button show.
But when i remove the condition under KeyEvent replace by
value.setOnKeyTyped(new EventHandler<KeyEvent>(){
#Override
public void handle(KeyEvent event) {
btn.setVisible(true);
}
});
Then btn show if any character input into the TextField
You may also prefer to use JavaFX binding mechanism:
#Override
public void start( final Stage primaryStage )
{
TextField textfield = new TextField();
Button button = new Button( "my button" );
button.visibleProperty().bind( textfield.textProperty().isEmpty().not() );
final Scene scene = new Scene( new HBox( button, textfield ), 800, 600 );
primaryStage.setScene( scene );
primaryStage.show();
}
The actual problem in your code:
You have attached a listener to field when "OnKeyTyped", at this stage the newly typed text is not appended to the textfield's text value so your if-else condition will not see it. Instead, the correct way should be attaching the listener on "OnKeyReleased".
Add a listener to the textProperty() of the TextField. Check if the value is empty, hide the button else show it. It will be called whenever a character is added or removed from the textfield.
Here is a MCVE, you can just add the listener to the initialize method of the controller.
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class HideButtonOnTextEntered extends Application {
#Override
public void start(Stage stage) {
TextField textField = new TextField();
Button button = new Button("Button");
button.setVisible(false);
VBox root = new VBox(20, textField, button);
root.setAlignment(Pos.CENTER);
Scene scene = new Scene(root, 200, 200);
stage.setScene(scene);
stage.show();
textField.textProperty().addListener((ov, oldValue, newValue) -> {
if (newValue.isEmpty()) {
button.setVisible(false);
} else {
button.setVisible(true);
}
});
}
public static void main(String[] args) {
launch(args);
}
}

LWUIT TextArea text formatting how to?

I work on a LWUIT project that aims to computerize an Arabic book . That means each page of the
mentioned book accessed by a specific button
returns
To do that I created a form , array of buttons, and a textarea.
The setText( ) method of textarea widget is used to involve each page of the book
How?
When a button pressed
the setText( ) changes it's string according to the content of the
required page
returns
At the end of the project a problem of formatting faces me .
The book page's contents (Strings ) are unformatted.
returns
to solve the problem I tried a LWUIT HtmlComponent instead of textArea in order to format using
html tags , but it takes much of memory
(at least it cost more than 700 kb for an application).
So I wouldn't be able include all the pages of the book by this way.
returns
This my first trial
import javax.microedition.midlet.*;
import com.sun.lwuit.events.*;
import javax.microedition.midlet.*;
import com.sun.lwuit.layouts.*;
import com.sun.lwuit.*;
public class Arabic_Lang extends MIDlet {
public void startApp()
{
com.sun.lwuit.Display.init(this);
final com.sun.lwuit.Form main_form = new com.sun.lwuit.Form();
final com.sun.lwuit.Form f = new com.sun.lwuit.Form();
final com.sun.lwuit.TextArea txt1 = new com.sun.lwuit.TextArea();
f.addComponent(txt1);
final com.sun.lwuit.Button l[]= new com.sun.lwuit.Button [3];
final com.sun.lwuit.Button inter = new com.sun.lwuit.Button("inter");
final com.sun.lwuit.Form jjj8 = new com.sun.lwuit.Form();
jjj8.setTitle( "اللغة العربية");
jjj8.getStyle().setBgColor(0x006699);
jjj8.setScrollableX(true);
int i;
for(i=0;i<3;i++)
{
l[i] =new com.sun.lwuit.Button();
l[i].getStyle().setBgColor(0xFFF66);
main_form.addComponent(l[i]);
main_form.setScrollable (true);
main_form.setScrollableX(false);
}
l[0].setText("");
l[0].getStyle().setBgColor(0xffff00);
l[0].setText("arabic");
l[1].setText("arabic");
l[0].addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae) {
txt1.setText(" \u0628 \u0639\u0644\u0649 \u0644\u063A\u062A");
}
});
l[1].addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae) {
txt1.setText(" \u0628 \u0639\u0644\u0649 \u0644\u063A\u062A");
f.show();
}
});
jjj8.addComponent(inter);
inter.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae) {
main_form.show();
}
}
);
jjj8.show();
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
}
returns
And this is my trial to use htmlComponent
returns
import com.sun.lwuit.layouts.*;
import javax.microedition.midlet.*;
public class HelloLWUITMidlet3 extends MIDlet
{
public void startApp()
{
com.sun.lwuit.Display.init(this);
final com.sun.lwuit.Form form = new com.sun.lwuit.Form("");
final com.sun.lwuit.html.HTMLComponent htmlC = new com.sun.lwuit.html.HTMLComponent( );
htmlC.setRTL(true);
htmlC.setBodyText("هذه لغة عربية","UTF-8" );
form.addComponent(htmlC);
BorderLayout bl = new BorderLayout();
form.setScrollable(true);
form.show( );
}
public void pauseApp()
{
}
public void destroyApp(boolean unconditional) {
}
}
Store the pages of the book as HTML files in your src dir (in the jar root) and load them directly into the HTMLComponent as is shown in the LWUITDemo.

Using a Command to switch to a Displayable in a class that extends MIDlet

I'm working in java me. I'm trying to switch between visual designs using ok Commands and back Commands. I have a form displayable which I named formA in my main class A.java and a formB in another class B.java . I used an ok Command in formA which on selection, is supposed to take the user to formB.
I created a reference to B.java in my main class A.java constructor
B b;
// A.java constructor
public A() {
b = new B(this);
}
now I could call the getFormB method from my commandAction in formA. Then I added a backCommand which is supposed to take me back to formA in A.java and I tried creating a reference in B.java same way I did in A.java but I get a SecurityException MIDletManager ERROR at runtime. I was adviced to add an A attribute to my B class and receive the instance as a constructor parameter so I can call the getFormA() method to switch to formA in A.java
A a;
B(A a) {
this.a = a;
}
in command action I did ds on the backCommand:
switchDisplayable ( null , a.getFormA());
This compiled, but at runtime on hitting the BACK key from formB I get java/lang/NullPointerException.
Can anyone tell me why this happended and how to fix it please. All I'm trying to acheive is the backCommand to take the user back to formA from formB
If your A class extends Form or your A class is Displayable, then in the Back command, you can just tell switchDisplayable(null, a).
If your A class is not a Form, then make sure your A class has the following methods:
public Form getFormA() {
return ...; // return the `Form` here so you will not get NullPointerException
}
UPDATE:
If you're using NetBeans, you can open Flow tab and drag backCommand from formB to formA. NetBeans will generate the required code for you.
If you code by hand, then it will looks like the following:
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
public class ExampleMidlet extends MIDlet {
private Display display;
private Form formA;
private Form formB;
private Command formA_next;
private Command formB_back;
public void startApp() {
if (display==null) {
display = Display.getDisplay(this);
formA = new Form("Form A");
formA_next = new Command("Next", Command.SCREEN, 0);
formA.addCommand(formA_next);
formA.setCommandListener(new CommandListener() {
public void commandAction(Command c, Displayable d) {
if (c==formA_next) {
display.setCurrent(formB);
}
}
});
formB = new Form("Form B");
formB_back = new Command("Back", Command.BACK, 0);
formB.addCommand(formB_back);
formB.setCommandListener(new CommandListener() {
public void commandAction(Command c, Displayable d) {
if (c==formB_back) {
display.setCurrent(formA);
}
}
});
}
display.setCurrent(formA);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
}
I don't know how you code your Form, but it seems that a is null. Maybe you can show me the full code. Passing this in constructor is generally not recommended. By the way, you still need a 'main' class that extends MIDlet right? Then there will be 3 classes, such as:
ExampleMiddlet.java (this is where you put your MIDlet lifecycle, such as startApp(), pauseApp(), etc):
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
public class ExampleMidlet extends MIDlet {
private Display display;
private Form formA, formB;
public void startApp() {
if (display==null) {
display = Display.getDisplay(this);
formA = new FormA(this);
formB = new FormB(this);
}
display.setCurrent(formA);
}
public Form getFormA() {
return formA;
}
public Form getFormB() {
return formB;
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
}
FormA.java (this is where you put the content of your Form):
import javax.microedition.lcdui.*;
public class FormA extends Form {
private Command cmdNext;
public FormA(final ExampleMidlet midlet) {
super("Form A");
append("This is form A.");
cmdNext = new Command("Next", Command.SCREEN, 0);
addCommand(cmdNext);
setCommandListener(new CommandListener() {
public void commandAction(Command c, Displayable d) {
Display.getDisplay(midlet).setCurrent(midlet.getFormB());
}
});
}
}
FormB.java (this is where you put the content of your Form):
import javax.microedition.lcdui.*;
public class FormB extends Form {
private Command cmdBack;
public FormB(final ExampleMidlet midlet) {
super("Form B");
append("This is form B.");
cmdBack = new Command("Back", Command.SCREEN, 0);
addCommand(cmdBack);
setCommandListener(new CommandListener() {
public void commandAction(Command c, Displayable d) {
Display.getDisplay(midlet).setCurrent(midlet.getFormA());
}
});
}
}

Confused with command listeners and new forms J2ME

EDIT: I believe I need help getting the selected element in the list I just managed
for it to display a new form but I'm having a lot of trouble finding code that workswith source 3.0.
I've been trying to make a application that allows a user to select a date then add
and remove events based on the selected date. So far I have created the first screen
which is a list of option for the user to choose from. These options are:
Select Date
Add Events
Remove Events
Browse Events
The issues I'm having is I can't get my head around how to display new forms based on the selected Item in the list. I found a small tutorial that allowed me to add a commandlistener which shows the selected item but I'm having trouble figuring out how it gets the item selected in the list and how I could create a new form based on the item selected?
Here's my code so far.
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.List;
import javax.microedition.lcdui.Form;
import javax.microedition.midlet.MIDlet;
public class mainMidlet extends MIDlet implements CommandListener {
private Display display;
private List list = new List("Please Select a Option", List.IMPLICIT);
private Command select = new Command("Select", Command.SCREEN, 1);
private Form form;
Alert alert;
public mainMidlet() {
display = Display.getDisplay(this);
list.append("Select Date", null);
list.append("Add Events", null);
list.append("Remove Events", null);
list.append("Browse Events", null);
list.addCommand(select);
list.setCommandListener(this);
}
public void startApp() {
display.setCurrent(list);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public void commandAction(Command command, Displayable displayable) {
if (command == List.SELECT_COMMAND) {
String selection = list.getString(list.getSelectedIndex());
alert = new Alert("Option Selected", selection, null, null);
alert.setTimeout(Alert.FOREVER);
alert.setType(AlertType.INFO);
display.setCurrent(alert);
} else if (command == select) {
destroyApp(false);
notifyDestroyed();
}
}
}
You can add several forms and switch between them
public void commandAction(Command command, Displayable displayable) {
if (displayable == list) {
if (command == List.SELECT_COMMAND) {
switch (list.getSelectedIndex()) {
case 0: // select date
display.setCurrent(someForm);
break;
case 1: //add events
display.setCurrent(someOtherForm);
break;
}
} else if (command == select) {
destroyApp(false);
notifyDestroyed();
}
}
if (displayable == someForm) {
//but it's better practice to make each form a different class implementing CommandListener and it's own commandAction. And leave the display public static in MIDlet class
//...
}
}

nokia device vibration in a game using j2me

I want to make my phone vibrate when my game ends. I tried using
Display display = Display.getDisplay(midlet);
display.vibrate(2000);
but display.vibrate(2000) returns false and the device does not vibrate.
Can anyone help.
I am trying it on Nokia C7 device. (Symbian^3)
According to Display.vibrate documentation "The return value indicates if the vibrator can be controlled by the application." If you are calling vibrate during destroyApp the VM might be ignoring the vibrate request.
Try calling Display.vibrate before you call MIDlet.notifyDestroyed
Try this code and see if it works.
It worked for me on nokia e63
package ravi.vibrationClass;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
public class Vibrate extends MIDlet implements CommandListener{
Form form;
Display disp;
Command vib,exit;
public void startApp() {
form = new Form("Vibration");
disp = Display.getDisplay(this);
exit = new Command("Exit", Command.EXIT, 1);
vib = new Command("Vibrate", Command.OK, 1);
form.append("Press \"vibrate\" to make the phone vibrate");
form.addCommand(vib);
form.addCommand(exit);
form.setCommandListener(this);
disp.setCurrent(form);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
notifyDestroyed();
}
public void commandAction(Command c, Displayable arg1) {
if(c == vib){
disp.vibrate(125);
}else if(c == exit){
destroyApp(true);
}
}
}

Resources