Midlet Timer J2ME Wireless toolkit 2.5.2_0.1 for CLDC - java-me

Could some one please tell me whay I cant Built this code? There is something wrong with Gauge but I dont understand what or what I need to change.
It show me error when I try to Bulid.
Building "Alert01"
warning: [options] source value 1.3 is obsolete and will be removed in a future release
warning: [options] target value 1.3 is obsolete and will be removed in a future release
warning: [options] To suppress warnings about obsolete options, use -Xlint:-options.
C:\Users\Benita\j2mewtk\2.5.2\apps\Alert01\src\Alert01.java:112: error: cannot find symbol
alert.setIndicator(gauge);
^
symbol: method setIndicator(Gauge)
location: variable alert of type Alert
1 error
3 warnings
com.sun.kvem.ktools.ExecutionException
Build failed
Bulding this code
package Alert01;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.TextBox;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.MIDlet;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Date;
import javax.microedition.lcdui.Gauge;
public class Alert01 extends MIDlet{
Alert01 theMidlet;
Image image;
int count = 0;
long baseTime;
public Alert01(){
System.out.println("Construct MIDlet");
theMidlet = this;
baseTime = new Date().getTime()/1000;
}//end constructor
//----------------------------------------------------//
public void startApp(){
System.out.println("Create and display a TextBox");
TextBox textBox = new TextBox("TextBox Title",
"TextBox contents",
50,//width
TextField.ANY);
//Make the TextBox the current Displayable object.
Display.getDisplay(this).setCurrent(textBox);
//Now create and schedule a TimerTask that will
// display and sound an alert repeatedly. The Alert
// first appears at two seconds and repeats every
// three seconds.
Timer myTimer = new Timer();
myTimer.schedule(new MyTimerTask(),2000,3000);
//Sleep for 20 seconds.
try{Thread.currentThread().sleep(20000);
} catch(Exception e){}
//Cancel the timer.
myTimer.cancel();
//Enter the destroyed state.
this.destroyApp(true);
}//end startApp
public void pauseApp(){
}//end pauseApp
public void destroyApp(boolean unconditional){
System.out.println("Destroy MIDlet");
notifyDestroyed();
}//end destroyApp
//----------------------------------------------------//
//This is a member class
class MyTimerTask extends TimerTask{
long time;
public void run(){
System.out.println("Display an Alert");
try{
//Select among two image files on the basis of
// whether the current time in seconds is odd
// or even.
time = new Date().getTime()/1000 - baseTime;
//Note that the following file names are case
// sensitive.
if((time % 2) == 0){//Even value
image = Image.createImage(
"/Alert01/redball.PNG");
}else{//Odd value
image = Image.createImage(
"/Alert01/blueball.PNG");
}//end else
//Create an Alert object of type ALARM. This
// results in an audible alarm that sounds like a
// telephone ringing.
Alert alert = new Alert("Alert Title",
"",
image,
AlertType.ALARM);
//Cause the alert to display the time in seconds.
alert.setString("Time in seconds:" + time);
//Cause the alert to be visible for two seconds.
alert.setTimeout(2000);
//Create a Gauge that shows six bars.
Gauge gauge = new Gauge(null,false,6,0);
//Set the number of Gauge bars to be illuminated.
gauge.setValue(++count);
//Attach the Gauge to the alert.
alert.setIndicator(gauge);
//Make the Alert the current Displayable object.
Display.getDisplay(theMidlet).setCurrent(alert);
}catch(Exception e){
e.printStackTrace();
}//end catch
}//end run
}//end class MyTimerTask
//====================================================//
}//end class Alert01
//======================================================//

The setIndicator method is available on MIDP 2.0. You are probably compiling with MIDP 1.0.

Related

JavaFX Image Loading in Background and Threads

I thought this would be a simple question but I am having trouble finding an answer. I have a single ImageView object associated with a JavaFX Scene object and I want to load large images in from disk and display them in sequence one after another using the ImageView. I have been trying to find a good way to repeatedly check the Image object and when it is done loading in the background set it to the ImageView and then start loading a new Image object. The code I have come up with (below) works sometimes and sometimes it doesn't. I am pretty sure I am running into issues with JavaFX and threads. It loads the first image sometimes and stops. The variable "processing" is a boolean instance variable in the class.
What is the proper way to load an image in JavaFX in the background and set it to the ImageView after it is done loading?
public void start(Stage primaryStage) {
...
ImageView view = new ImageView();
((Group)scene.getRoot()).getChildren().add(view);
...
Thread th = new Thread(new Thread() {
public void run() {
while(true) {
if (!processing) {
processing = true;
String filename = files[count].toURI().toString();
Image image = new Image(filename,true);
image.progressProperty().addListener(new ChangeListener<Number>() {
#Override public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number progress) {
if ((Double) progress == 1.0) {
if (! image.isError()) {
view.setImage(image);
}
count++;
if (count == files.length) {
count = 0;
}
processing = false;
}
}
});
}
}
}
});
}
I actually think there's probably a better general approach to satisfying whatever your application's requirements are than the approach you are trying to use, but here is my best answer at implementing the approach you describe.
Create a bounded BlockingQueue to hold the images as you load them. The size of the queue may need some tuning: too small and you won't have any "buffer" (so you won't be able to take advantage of any that are faster to load than the average), too large and you might consume too much memory. The BlockingQueue allows you to access it safely from multiple threads.
Create a thread that simply loops and loads each image synchronously, i.e. that thread blocks while each image loads, and deposits them in the BlockingQueue.
Since you want to try to display images up to once per FX frame (i.e. 60fps), use an AnimationTimer. This has a handle method that is invoked on each frame render, on the FX Application Thread, so you can implement it just to poll() the BlockingQueue, and if an image was available, set it in the ImageView.
Here's an SSCCE. I also indicated how to do this where you display each image for a fixed amount of time, as I think that's a more common use case and might help others looking for similar functionality.
import java.io.File;
import java.net.MalformedURLException;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javafx.animation.AnimationTimer;
import javafx.animation.PauseTransition;
import javafx.application.Application;
import javafx.concurrent.Task;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.stage.DirectoryChooser;
import javafx.stage.Stage;
public class ScreenSaver extends Application {
#Override
public void start(Stage primaryStage) {
BorderPane root = new BorderPane();
Button startButton = new Button("Choose image directory...");
startButton.setOnAction(e -> {
DirectoryChooser chooser= new DirectoryChooser();
File dir = chooser.showDialog(primaryStage);
if (dir != null) {
File[] files = Stream.of(dir.listFiles()).filter(file -> {
String fName = file.getAbsolutePath().toLowerCase();
return fName.endsWith(".jpeg") | fName.endsWith(".jpg") | fName.endsWith(".png");
}).collect(Collectors.toList()).toArray(new File[0]);
root.setCenter(createScreenSaver(files));
}
});
root.setCenter(new StackPane(startButton));
primaryStage.setScene(new Scene(root, 800, 800));
primaryStage.show();
}
private Parent createScreenSaver(File[] files) {
ImageView imageView = new ImageView();
Pane pane = new Pane(imageView);
imageView.fitWidthProperty().bind(pane.widthProperty());
imageView.fitHeightProperty().bind(pane.heightProperty());
imageView.setPreserveRatio(true);
Executor exec = Executors.newCachedThreadPool(runnable -> {
Thread t = new Thread(runnable);
t.setDaemon(true);
return t ;
});
final int imageBufferSize = 5 ;
BlockingQueue<Image> imageQueue = new ArrayBlockingQueue<Image>(imageBufferSize);
exec.execute(() -> {
int index = 0 ;
try {
while (true) {
Image image = new Image(files[index].toURI().toURL().toExternalForm(), false);
imageQueue.put(image);
index = (index + 1) % files.length ;
}
} catch (MalformedURLException e) {
throw new RuntimeException(e);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
// This will show a new image every single rendering frame, if one is available:
AnimationTimer timer = new AnimationTimer() {
#Override
public void handle(long now) {
Image image = imageQueue.poll();
if (image != null) {
imageView.setImage(image);
}
}
};
timer.start();
// This wait for an image to become available, then show it for a fixed amount of time,
// before attempting to load the next one:
// Duration displayTime = Duration.seconds(1);
// PauseTransition pause = new PauseTransition(displayTime);
// pause.setOnFinished(e -> exec.execute(createImageDisplayTask(pause, imageQueue, imageView)));
// exec.execute(createImageDisplayTask(pause, imageQueue, imageView));
return pane ;
}
private Task<Image> createImageDisplayTask(PauseTransition pause, BlockingQueue<Image> imageQueue, ImageView imageView) {
Task<Image> imageDisplayTask = new Task<Image>() {
#Override
public Image call() throws InterruptedException {
return imageQueue.take();
}
};
imageDisplayTask.setOnSucceeded(e -> {
imageView.setImage(imageDisplayTask.getValue());
pause.playFromStart();
});
return imageDisplayTask ;
}
public static void main(String[] args) {
launch(args);
}
}

Adding gauge in location finder class in j2me

I am working on a j2me application which contain a class to find the location of mobile using GPS.I need to include gauge while the location provider API is called and it finds the location.I am new to j2me so still not clear with all the concepts.I am pasting my code below.Please help me through this.Thanks in advance..
package org.ets.utils;
import javax.microedition.lcdui.*;
import javax.microedition.location.*;
import javax.microedition.io.*;
import java.io.*;
import org.ets.midlet.ETS_infozech;
import javax.microedition.midlet.*;
public class Locfinder {
public Locfinder(ETS_infozech midlet)
{
this.midlet = midlet;
}
public static String ex()
{
try {
checkLocation();
} catch (Exception ex)
{
ex.printStackTrace();
}
//System.out.println(string);
return string;
}
public static void checkLocation() throws Exception
{
Location l;
LocationProvider lp;
Coordinates c;
// Set criteria for selecting a location provider:
// accurate to 500 meters horizontally
Criteria cr= new Criteria();
cr.setHorizontalAccuracy(500);
// Get an instance of the provider
lp= LocationProvider.getInstance(cr);
//Request the location, setting a one-minute timeout
l = lp.getLocation(60);
c = l.getQualifiedCoordinates();
if(c != null ) {
// Use coordinate information
double lat = c.getLatitude();
double lon = c.getLongitude();
string = " LAT-" + lat + " LONG-" + lon;
}
}
}
There's no way you can link a Gauge to some task.
You have to set values to the Gauge manually. So you'd create a Gauge and add it to your Form. Then start your code to perform the look-up.
In between your lines of code, you'd add myGauge.setValue(some_value); to increase the indicator.
Of course, this becomes difficult when most of the task is contained in a single line of code, like e.g. lp.getLocation(60);.
I think, in that case, I would create a Thread that automatically increases the value on the Gauge in the 60 seconds, but can be stopped/overridden by a manual setting.
class Autoincrementer implements Runnable {
private boolean running;
private Gauge gauge;
private int seconds;
private int secondsElapsed;
public Autoincrementer(Gauge gauge) {
this.gauge = gauge;
this.seconds = gauge.getMaxValue();
this.running = true;
this.secondsElapsed = 0;
}
public void run() {
if (running) {
secondsElapsed++;
gauge.setValue(secondsElapsed);
if (secondsElapsed>=gauge.getMaxValue()) running = false; // Stop the auto incrementing
try {
Thread.sleep(1000); // Sleep for 1 second
} catch (Exception e) {}
}
}
public void stop() {
running = false;
}
}
You would then create a Gauge and add it to your Form
myGauge = new Gauge("Process", false, 60, 0);
myForm.append(myGauge);
Then start the auto-increment.
myIncrementer = new Autoincrementer(myGauge);
new Thread(myIncrementer).start();
And then call your look-up code.
checkLocation();
Inside your look-up code, add code to stop the auto-incrementing and set the Gauge object to 100%, if the look-up was successful (meaning before the timeout).
myIncrementer.stop();
myGauge.setValue(60);
LWUIT 1.5 can help you in this. Am not sure for Location API which you are using.
But you will get Gauge using LWUIT 1.5. Use Lwuit instead of LCDUI.
http://www.oracle.com/technetwork/java/javame/javamobile/download/lwuit/index.html

JavaFX: How to bind two values?

I'm new guy here :)
I have a small problem which concerns binding in JavaFX. I have created Task which is working as a clock and returns value which has to be set in a special label (label_Time). This label presents how many seconds left for player's answer in quiz.
The problem is how to automatically change value in label using the timer task? I tried to link value from timer Task (seconds) to label_Time value in such a way...
label_Time.textProperty().bind(timer.getSeconds());
...but it doesn't work. Is it any way to do this thing?
Thanks in advance for your answer! :)
Initialize method in Controller class:
public void initialize(URL url, ResourceBundle rb) {
Timer2 timer = new Timer2();
label_Time.textProperty().bind(timer.getSeconds());
new Thread(timer).start();
}
Task class "Timer2":
public class Timer2 extends Task{
private static final int SLEEP_TIME = 1000;
private static int sec;
private StringProperty seconds;
public Timer2(){
Timer2.sec = 180;
this.seconds = new SimpleStringProperty("180");
}
#Override protected StringProperty call() throws Exception {
int iterations;
for (iterations = 0; iterations < 1000; iterations++) {
if (isCancelled()) {
updateMessage("Cancelled");
break;
}
System.out.println("TIK! " + sec);
seconds.setValue(String.valueOf(sec));
System.out.println("TAK! " + seconds.getValue());
// From the counter we subtract one second
sec--;
//Block the thread for a short time, but be sure
//to check the InterruptedException for cancellation
try {
Thread.sleep(10);
} catch (InterruptedException interrupted) {
if (isCancelled()) {
updateMessage("Cancelled");
break;
}
}
}
return seconds;
}
public StringProperty getSeconds(){
return this.seconds;
}
}
Why your app does not work
What is happening is that you run the task on it's own thread, set the seconds property in the task, then the binding triggers an immediate update of the label text while still on the task thread.
This violates a rule for JavaFX thread processing:
An application must attach nodes to a Scene, and modify nodes that are already attached to a Scene, on the JavaFX Application Thread.
This is the reason that your originally posted program does not work.
How to fix it
To modify your original program so that it will work, wrap the modification of the property in the task inside a Platform.runLater construct:
Platform.runLater(new Runnable() {
#Override public void run() {
System.out.println("TIK! " + sec);
seconds.setValue(String.valueOf(sec));
System.out.println("TAK! " + seconds.getValue());
}
});
This ensures that when you write out to the property, you are already on the JavaFX application thread, so that when the subsequent change fires for the bound label text, that change will also occur on the JavaFX application thread.
On Property Naming Conventions
It is true that the program does not correspond to JavaFX bean conventions as Matthew points out. Conforming to those conventions is both useful in making the program more readily understandable and also for making use of things like the PropertyValueFactory which reflect on property method names to allow table and list cells to automatically update their values as the underlying property is updated. However, for your example, not following JavaFX bean conventions does not explain why the program does not work.
Alternate Solution
Here is an alternate solution to your countdown binding problem which uses the JavaFX animation framework rather than the concurrency framework. I prefer this because it keeps everything on the JavaFX application thread and you don't need to worry about concurrency issues which are difficult to understand and debug.
import javafx.animation.*;
import javafx.application.Application;
import javafx.beans.*;
import javafx.beans.binding.Bindings;
import javafx.beans.property.*;
import javafx.event.*;
import javafx.geometry.Pos;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.util.Duration;
public class CountdownTimer extends Application {
#Override public void start(final Stage stage) throws Exception {
final CountDown countdown = new CountDown(10);
final CountDownLabel countdownLabel = new CountDownLabel(countdown);
final Button countdownButton = new Button(" Start ");
countdownButton.setOnAction(new EventHandler<ActionEvent>() {
#Override public void handle(ActionEvent t) {
countdownButton.setText("Restart");
countdown.start();
}
});
VBox layout = new VBox(10);
layout.getChildren().addAll(countdownLabel, countdownButton);
layout.setAlignment(Pos.BASELINE_RIGHT);
layout.setStyle("-fx-background-color: cornsilk; -fx-padding: 20; -fx-font-size: 20;");
stage.setScene(new Scene(layout));
stage.show();
}
public static void main(String[] args) throws Exception {
launch(args);
}
}
class CountDownLabel extends Label {
public CountDownLabel(final CountDown countdown) {
textProperty().bind(Bindings.format("%3d", countdown.timeLeftProperty()));
}
}
class CountDown {
private final ReadOnlyIntegerWrapper timeLeft;
private final ReadOnlyDoubleWrapper timeLeftDouble;
private final Timeline timeline;
public ReadOnlyIntegerProperty timeLeftProperty() {
return timeLeft.getReadOnlyProperty();
}
public CountDown(final int time) {
timeLeft = new ReadOnlyIntegerWrapper(time);
timeLeftDouble = new ReadOnlyDoubleWrapper(time);
timeline = new Timeline(
new KeyFrame(
Duration.ZERO,
new KeyValue(timeLeftDouble, time)
),
new KeyFrame(
Duration.seconds(time),
new KeyValue(timeLeftDouble, 0)
)
);
timeLeftDouble.addListener(new InvalidationListener() {
#Override public void invalidated(Observable o) {
timeLeft.set((int) Math.ceil(timeLeftDouble.get()));
}
});
}
public void start() {
timeline.playFromStart();
}
}
Update for additional questions on Task execution strategy
Is it possible to run more than one Task which includes a Platform.runLater(new Runnable()) method ?
Yes, you can use multiple tasks. Each task can be of the same type or a different type.
You can create a single thread and run each task on the thread sequentially, or you can create multiple threads and run the tasks in parallel.
For managing multiple tasks, you can create an overseer Task. Sometimes it is appropriate to use a Service for managing the multiple tasks and the Executors framework for managing multiple threads.
There is an example of a Task, Service, Executors co-ordination approach: Creating multiple parallel tasks by a single service In each task.
In each task you can place no runlater call, a single runlater call or multiple runlater calls.
So there is a great deal of flexibility available.
Or maybe I should create one general task which will be only take data from other Tasks and updating a UI?
Yes you can use a co-ordinating task approach like this if complexity warrants it. There is an example of such an approach in in Render 300 charts off screen and save them to files.
Your "Timer2" class doesn't conform to the JavaFX bean conventions:
public String getSeconds();
public void setSeconds(String seconds);
public StringProperty secondsProperty();

Lwuit touch screen strange behaviour

I am making an application using LWUIT.
There is a form
There is a list embedded on the form.
The list has 5 elements.
Initially, when I first load the app, if I choose the 1st element, 2nd gets chosen; when I choose the second the 3rd gets chose and and so on (Weird!)
I am not able to click any button on the screen either
next what I do is, shift to a different from using arrow keys (of the keyboard... I am running the app on a simulator btw)
Then I come back to the first form and now everything works as expected(no weird behaviour).
What could be the issue?
I am using Sun Java Micro Edition SDK 3.0 (default touch screen for testing)
My code is:
List dummy = new List();
dummy.addItem("wewerwer");
dummy.addItem("wewerdswer");
dummy.addItem("wewqweerwer");
dummy.addItem("dscxwewerwer");
dummy.addItem("jhgwewerwer");
mainListForm.setLayout(new BorderLayout());
mainListForm.addComponent(BorderLayout.CENTER,dummy);
mainListForm.show();
What could possible be going wrong here?
UPDATE 1
I think there is a bug here. I have attached the complete code below along with the screen shot
import javax.microedition.midlet.*;
import com.sun.lwuit.*;
import com.sun.lwuit.events.*;
import com.sun.lwuit.plaf.UIManager;
import com.sun.lwuit.util.Resources;
public class Demo extends MIDlet implements ActionListener {
private Form mForm;
List abc;
public void startApp() {
Display.init(this);
try {
Resources r = Resources.open("/Test.res");
UIManager.getInstance().setThemeProps(r.getTheme(
r.getThemeResourceNames()[0])
);
} catch (Exception e){
System.out.println(e.toString());
}
if (mForm == null) {
Button click = new Button("Press me!");
click.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
System.out.println("I have been pressed");
}
});
abc = new List();
abc.addItem("Str1");
abc.addItem("Str2");
abc.addItem("Str3");
abc.addItem("Str4");
abc.addItem("Str5");
abc.addItem("Str6");
Form f = new Form("Hello, LWUIT!");
abc.addActionListener(this);
f.addComponent(abc);
Command exitCommand = new Command("Exit");
f.addCommand(exitCommand);
f.addCommandListener(this);
f.addComponent(click);
f.show();
}
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public void actionPerformed(ActionEvent ae) {
System.out.println(abc.getSelectedIndex());
}
}
So now when I click on 'Str1' of the list Str2 gets selected and so on.
IDE: Netbeans
Emulator: Default Touch screen phone
On the action event set the list to active again after the event by invoking setHandlesInput(true)
OK....so this is how you resolve it.
After the form is displayed remove the list from the form and again add it to the form and then repaint the form.
Earlier Code
1) form.addComponenet(BorderLayout.center,list);
2) form.show();
Word Around for the problem
1)form.addComponenet(BorderLayout.center,list);
2)form.show();
3)form.setScrollable(false);
I know its kind of strange, but this way the list index selection works smooth for touch screen phones.

How can I tell what events fire from GXT?

I cannot seem to find any documentation of what events fire and when in GXT.
The API docs have lists of all the events that could fire (in Events). And it describes how to handle events that you catch. But I'm interested in the opposite side, which events are fired when I take a certain action.
I can set some listeners for various different components, or I can use addListener with a specific event code to catch individual events. That's spotty, and I seem to be using trial-and-error to guess what I might want to catch.
Is there a way to log all the events that are firing? Or catch all of them so I could look at them in a debugger?
Or is there some documentation I am missing that has the information? Something along the lines of "when you click on a widget, a ButtonEvent is fired. Events.x is fired on the hover, Events.y on the click."
Maybe someone will find this useful, I've created utility class for seeing what kind of events are risen. The idea of course was proposed in accepted answer.
import java.util.HashMap;
import java.util.Map;
import com.extjs.gxt.ui.client.event.BaseEvent;
import com.extjs.gxt.ui.client.event.EventType;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.widget.Component;
/**
* Class for debugging purposes. Sometimes it is hard to tell what type of event
* is invoked and when. During debug process you can just do:
*
* EventUtils.attachDebugListeners(c);
* EventUtils.attachDebugListeners(c, "NAME");
*
* You'll then get information about events as they are invoked.
*
* List of events copied from {#link Events} class.
*
*/
public class EventUtils {
public static void attachDebugListeners(final Component c) {
attachDebugListeners(c, null);
}
public static void attachDebugListeners(final Component c, final String msg) {
for (final EventType type : eventTypeNames.keySet()) {
c.addListener(type, new Listener<BaseEvent>() {
#Override
public void handleEvent(BaseEvent be) {
String typeName = eventTypeNames.get(type);
if (msg != null)
System.out.print(msg + " -> ");
System.out.println(typeName);
}
});
}
}
final static Map<EventType, String> eventTypeNames = new HashMap<EventType, String>();
static {
eventTypeNames.put(Events.Activate, "Events.Activate");
eventTypeNames.put(Events.Add, "Events.Add");
eventTypeNames.put(Events.Adopt, "Events.Adopt");
eventTypeNames.put(Events.AfterEdit, "Events.AfterEdit");
eventTypeNames.put(Events.AfterLayout, "Events.AfterLayout");
eventTypeNames.put(Events.ArrowClick, "Events.ArrowClick");
eventTypeNames.put(Events.Attach, "Events.Attach");
eventTypeNames.put(Events.AutoHide, "Events.AutoHide");
eventTypeNames.put(Events.BeforeAdd, "Events.BeforeAdd");
eventTypeNames.put(Events.BeforeAdopt, "Events.BeforeAdopt");
eventTypeNames.put(Events.BeforeBind, "Events.BeforeBind");
eventTypeNames.put(Events.BeforeCancelEdit, "Events.BeforeCancelEdit");
eventTypeNames.put(Events.BeforeChange, "Events.BeforeChange");
eventTypeNames
.put(Events.BeforeCheckChange, "Events.BeforeCheckChange");
eventTypeNames.put(Events.BeforeClose, "Events.BeforeClose");
eventTypeNames.put(Events.BeforeCollapse, "Events.BeforeCollapse");
eventTypeNames.put(Events.BeforeComplete, "Events.BeforeComplete");
eventTypeNames.put(Events.BeforeEdit, "Events.BeforeEdit");
eventTypeNames.put(Events.BeforeExpand, "Events.BeforeExpand");
eventTypeNames.put(Events.BeforeHide, "Events.BeforeHide");
eventTypeNames.put(Events.BeforeLayout, "Events.BeforeLayout");
eventTypeNames.put(Events.BeforeOpen, "Events.BeforeOpen");
eventTypeNames.put(Events.BeforeOrphan, "Events.BeforeOrphan");
eventTypeNames.put(Events.BeforeQuery, "Events.BeforeQuery");
eventTypeNames.put(Events.BeforeRemove, "Events.BeforeRemove");
eventTypeNames.put(Events.BeforeRender, "Events.BeforeRender");
eventTypeNames.put(Events.BeforeSelect, "Events.BeforeSelect");
eventTypeNames.put(Events.BeforeShow, "Events.BeforeShow");
eventTypeNames.put(Events.BeforeStartEdit, "Events.BeforeStartEdit");
eventTypeNames.put(Events.BeforeStateRestore,
"Events.BeforeStateRestore");
eventTypeNames.put(Events.BeforeStateSave, "Events.BeforeStateSave");
eventTypeNames.put(Events.BeforeSubmit, "Events.BeforeSubmit");
eventTypeNames.put(Events.Bind, "Events.Bind");
eventTypeNames.put(Events.Blur, "Events.Blur");
eventTypeNames.put(Events.BodyScroll, "Events.BodyScroll");
eventTypeNames.put(Events.BrowserEvent, "Events.BrowserEvent");
eventTypeNames.put(Events.CancelEdit, "Events.CancelEdit");
eventTypeNames.put(Events.CellClick, "Events.CellClick");
eventTypeNames.put(Events.CellDoubleClick, "Events.CellDoubleClick");
eventTypeNames.put(Events.CellMouseDown, "Events.CellMouseDown");
eventTypeNames.put(Events.CellMouseUp, "Events.CellMouseUp");
eventTypeNames.put(Events.Change, "Events.Change");
eventTypeNames.put(Events.CheckChange, "Events.CheckChange");
eventTypeNames.put(Events.CheckChanged, "Events.CheckChanged");
eventTypeNames.put(Events.Clear, "Events.Clear");
eventTypeNames.put(Events.Close, "Events.Close");
eventTypeNames.put(Events.Collapse, "Events.Collapse");
eventTypeNames.put(Events.ColumnClick, "Events.ColumnClick");
eventTypeNames.put(Events.ColumnResize, "Events.ColumnResize");
eventTypeNames.put(Events.Complete, "Events.Complete");
eventTypeNames.put(Events.ContextMenu, "Events.ContextMenu");
eventTypeNames.put(Events.Deactivate, "Events.Deactivate");
eventTypeNames.put(Events.Detach, "Events.Detach");
eventTypeNames.put(Events.Disable, "Events.Disable");
eventTypeNames.put(Events.DoubleClick, "Events.DoubleClick");
eventTypeNames.put(Events.DragCancel, "Events.DragCancel");
eventTypeNames.put(Events.DragEnd, "Events.DragEnd");
eventTypeNames.put(Events.DragEnter, "Events.DragEnter");
eventTypeNames.put(Events.DragFail, "Events.DragFail");
eventTypeNames.put(Events.DragLeave, "Events.DragLeave");
eventTypeNames.put(Events.DragMove, "Events.DragMove");
eventTypeNames.put(Events.DragStart, "Events.DragStart");
eventTypeNames.put(Events.Drop, "Events.Drop");
eventTypeNames.put(Events.EffectCancel, "Events.EffectCancel");
eventTypeNames.put(Events.EffectComplete, "Events.EffectComplete");
eventTypeNames.put(Events.EffectStart, "Events.EffectStart");
eventTypeNames.put(Events.Enable, "Events.Enable");
eventTypeNames.put(Events.Exception, "Events.Exception");
eventTypeNames.put(Events.Expand, "Events.Expand");
eventTypeNames.put(Events.Focus, "Events.Focus");
eventTypeNames.put(Events.HeaderChange, "Events.HeaderChange");
eventTypeNames.put(Events.HeaderClick, "Events.HeaderClick");
eventTypeNames
.put(Events.HeaderContextMenu, "Events.HeaderContextMenu");
eventTypeNames
.put(Events.HeaderDoubleClick, "Events.HeaderDoubleClick");
eventTypeNames.put(Events.HeaderMouseDown, "Events.HeaderMouseDown");
eventTypeNames.put(Events.HiddenChange, "Events.HiddenChange");
eventTypeNames.put(Events.Hide, "Events.Hide");
eventTypeNames.put(Events.Invalid, "Events.Invalid");
eventTypeNames.put(Events.KeyDown, "Events.KeyDown");
eventTypeNames.put(Events.KeyPress, "Events.KeyPress");
eventTypeNames.put(Events.KeyUp, "Events.KeyUp");
eventTypeNames.put(Events.LiveGridViewUpdate,
"Events.LiveGridViewUpdate");
eventTypeNames.put(Events.Maximize, "Events.Maximize");
eventTypeNames.put(Events.MenuHide, "Events.MenuHide");
eventTypeNames.put(Events.MenuShow, "Events.MenuShow");
eventTypeNames.put(Events.Minimize, "Events.Minimize");
eventTypeNames.put(Events.Move, "Events.Move");
eventTypeNames.put(Events.OnBlur, "Events.OnBlur");
eventTypeNames.put(Events.OnChange, "Events.OnChange");
eventTypeNames.put(Events.OnClick, "Events.OnClick");
eventTypeNames.put(Events.OnContextMenu, "Events.OnContextMenu");
eventTypeNames.put(Events.OnDoubleClick, "Events.OnDoubleClick");
eventTypeNames.put(Events.OnError, "Events.OnError");
eventTypeNames.put(Events.OnFocus, "Events.OnFocus");
eventTypeNames.put(Events.OnKeyDown, "Events.OnKeyDown");
eventTypeNames.put(Events.OnKeyPress, "Events.OnKeyPress");
eventTypeNames.put(Events.OnKeyUp, "Events.OnKeyUp");
eventTypeNames.put(Events.OnLoad, "Events.OnLoad");
eventTypeNames.put(Events.OnLoseCapture, "Events.OnLoseCapture");
eventTypeNames.put(Events.OnMouseDown, "Events.OnMouseDown");
eventTypeNames.put(Events.OnMouseMove, "Events.OnMouseMove");
eventTypeNames.put(Events.OnMouseOut, "Events.OnMouseOut");
eventTypeNames.put(Events.OnMouseOver, "Events.OnMouseOver");
eventTypeNames.put(Events.OnMouseUp, "Events.OnMouseUp");
eventTypeNames.put(Events.OnMouseWheel, "Events.OnMouseWheel");
eventTypeNames.put(Events.OnScroll, "Events.OnScroll");
eventTypeNames.put(Events.Open, "Events.Open");
eventTypeNames.put(Events.Orphan, "Events.Orphan");
eventTypeNames.put(Events.Ready, "Events.Ready");
eventTypeNames.put(Events.Refresh, "Events.Refresh");
eventTypeNames.put(Events.Register, "Events.Register");
eventTypeNames.put(Events.Remove, "Events.Remove");
eventTypeNames.put(Events.Render, "Events.Render");
eventTypeNames.put(Events.Resize, "Events.Resize");
eventTypeNames.put(Events.ResizeEnd, "Events.ResizeEnd");
eventTypeNames.put(Events.ResizeStart, "Events.ResizeStart");
eventTypeNames.put(Events.Restore, "Events.Restore");
eventTypeNames.put(Events.RowClick, "Events.RowClick");
eventTypeNames.put(Events.RowDoubleClick, "Events.RowDoubleClick");
eventTypeNames.put(Events.RowMouseDown, "Events.RowMouseDown");
eventTypeNames.put(Events.RowMouseUp, "Events.RowMouseUp");
eventTypeNames.put(Events.RowUpdated, "Events.RowUpdated");
eventTypeNames.put(Events.Scroll, "Events.Scroll");
eventTypeNames.put(Events.Select, "Events.Select");
eventTypeNames.put(Events.SelectionChange, "Events.SelectionChange");
eventTypeNames.put(Events.Show, "Events.Show");
eventTypeNames.put(Events.SortChange, "Events.SortChange");
eventTypeNames.put(Events.SpecialKey, "Events.SpecialKey");
eventTypeNames.put(Events.StartEdit, "Events.StartEdit");
eventTypeNames.put(Events.StateChange, "Events.StateChange");
eventTypeNames.put(Events.StateRestore, "Events.StateRestore");
eventTypeNames.put(Events.StateSave, "Events.StateSave");
eventTypeNames.put(Events.Submit, "Events.Submit");
eventTypeNames.put(Events.Toggle, "Events.Toggle");
eventTypeNames.put(Events.TriggerClick, "Events.TriggerClick");
eventTypeNames.put(Events.TwinTriggerClick, "Events.TwinTriggerClick");
eventTypeNames.put(Events.UnBind, "Events.UnBind");
eventTypeNames.put(Events.Unregister, "Events.Unregister");
eventTypeNames.put(Events.Update, "Events.Update");
eventTypeNames.put(Events.Valid, "Events.Valid");
eventTypeNames.put(Events.ValidateDrop, "Events.ValidateDrop");
eventTypeNames.put(Events.ValidateEdit, "Events.ValidateEdit");
eventTypeNames.put(Events.ViewReady, "Events.ViewReady");
}
}
I ended up using brute force: Created a Map of EventType and name, then attach a Listener for each type of event that the component could receive. Then I just set a breakpoint inside the Listener, and I could see what events were received when anything happened.
If it hadn't been throwaway code, I would have cleaned it up into a utility class, not used an anonymous Listener class, etc.
final Map<EventType, String> eventTypeNames = new HashMap<EventType, String>();
eventTypeNames.put(Events.BeforeExpand, "BeforeExpand");
eventTypeNames.put(Events.Expand, "Expand");
...
eventTypeNames.put(Events.BeforeStateSave, "BeforeStateSave");
eventTypeNames.put(Events.StateSave, "StateSave");
for (EventType eventType : Arrays.asList(
Events.BeforeExpand,
Events.Expand,
...
Events.BeforeStateSave,
Events.StateSave
)) {
this.addListener(eventType, new Listener<BaseEvent>() {
public void handleEvent(final BaseEvent be) {
String type = eventTypeNames.get(be.getType());
String ev = be.toString();
}
});
}
The API docs for the various widgets describe what events will fire and when they will fire. For an example, let's say we wanted take an action any time a user chooses a new TabItem in a TabPanel.
TabPanel's API documentation (located at http://extjs.com/deploy/gxtdocs/com/extjs/gxt/ui/client/widget/TabPanel.html) shows several events; we're interested in Select:
Select : TabPanelEvent(container, item)
Fires after a item is selected.
container : this
item : the item that was selected
So, to capture the event (which it appears you understand, but I will include for completeness' sake) the process is to add a listener to the TabPanel, watching specifically for the Events.Select event:
tp.addListener(Events.Select, new Listener<TabPanelEvent>(){
public void handleEvent(TabPanelEvent be)
{
MessageBox.alert("Test", be.item.getText(), null);
}
});
Note that many events have a property called doit which you may set to false to cancel the event.
A complete code listing:
package edu.fresno.client;
import com.extjs.gxt.ui.client.Events;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.TabPanelEvent;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.TabItem;
import com.extjs.gxt.ui.client.widget.TabPanel;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.client.ui.RootPanel;
public class GWTSandbox implements EntryPoint {
public void onModuleLoad() {
TabPanel tp = new TabPanel();
TabItem ti1 = new TabItem("TabItem1");
TabItem ti2 = new TabItem("TabItem2");
tp.add(ti1);
tp.add(ti2);
tp.addListener(Events.Select, new Listener<TabPanelEvent>(){
public void handleEvent(TabPanelEvent be)
{
MessageBox.alert("Test", be.item.getText(), null);
}
});
ContentPanel panel = new ContentPanel();
panel.setLayout(new FitLayout());
panel.add(tp);
RootPanel.get().add(panel);
}
}
You could add following code for the constructor:
ContentPanel panel =new ContentPanel(){
public boolean fireEvent(EventType type) {
System.out.println(type.getEventCode());
return super.fireEvent(type);
}
public boolean fireEvent(EventType eventType, BaseEvent be) {
System.out.println(eventType.getEventCode());
return super.fireEvent(eventType, be);
}
public boolean fireEvent(EventType type, ComponentEvent ce) {
System.out.println(type.getEventCode());
return super.fireEvent(type, ce);
}
};
then it will print any event this component can receive.

Resources