I'm new to Unity and am currently using Unity2D. What I want to do is that when a button is pressed an object moves and goes to a specific location. Currently I'm using:
public class MoveCard : MonoBehaviour
{
public float speed = 20f;
public Rigidbody2D rb;
public Vector2 pos = new Vector2(5,1);
void Update(){
}
void CardMovement(){
rb.MovePosition(pos * speed * Time.deltaTime);
}
}
I want the function CardMovement to initiate when I press a button, but it's not showing up in the Button Inspector and I don't know how to reference a Rigidbody2D in a button. How do I do this?
In the inspector in the buttons 'OnClickEvent' menu, click the plus button, drop in the object that contains 'MoveCard' component. In the drop box on the right find the method 'CardMovement'. Just a note in your current code you have it set up so if you press the button it will move only one frame's worth of movement. You could change to something like this:
public class MoveCard : MonoBehaviour
{
public float speed = 20f;
public Rigidbody2D rb;
public Vector2 pos = new Vector2(5,1);
public bool moving = false;
void Update(){
if (moving) {
rb.MovePosition(pos * speed * Time.deltaTime);
}
}
void CardMovement(){
moving = true;
}
}
edit (still not a bad idea):
//..
void FixedUpdate()
{
if (moving) {
rb.MovePosition(pos * Time.fixedDeltaTime);
}
}
//..
edit edit: set isKinematic to true on the rigidbody
The function your button is calling should be public.
public void CardMovement(){
rb.MovePosition(pos * speed * Time.deltaTime);
}
}
After you change it, assign again the object that has the script and try.
what you have to do is make a function in a script and apply that script to a game object. after making that create the button and click on the add function button to the button and drag the gameobject into the open section. afterwards chose the function from the listed scripts you added and have it call the move object script or whatever you called it.
I have a Trade class which contains a property currentPrice, which downloads price data from a website using getPricedata() method. The Trade object will show up as a table row in TableView. Now, my task: is to
use the getPricedata() method to grab data from internet, populate the currentPrice cell, whenever the object is created.
relaunch the getPricedata() method to every 1 minute after the object has been created and update table cell.
Below is the basic structure of my code. But I have no idea how to implement this ?
Which package do I need ? Task ? Service ? ScheduledService ?
public class Trade{
private DoubleProperty currentPrice;
// need thread here
public double getPricedata(){
.......
}
}
Use a ScheduledService<Number>, whose Task<Number>'s call() method retrieves and returns the value. Then you can either register an onSucceeded handler with the service, or just bind the Trade's currentPrice to service.lastValue(). Call setPeriod(..) on the service (once) to configure it to run every minute.
Since the currentPrice is being set from the service, you should only expose a ReadOnlyDoubleProperty from your Trade class (otherwise you might try to call currentPriceProperty().set(...) or setCurrentPrice(...), which would fail as it's bound).
I would do something like
public class Trade {
private final ReadOnlyDoubleWrapper currentPrice ;
private final ScheduledService<Number> priceService = new ScheduledService<Number>() {
#Override
public Task<Number> createTask() {
return new Task<Number>() {
#Override
public Number call() {
return getPriceData();
}
};
}
};
public Trade() {
priceService.setPeriod(Duration.minutes(1));
// in case of errors running service:
priceService.setOnFailed(e -> priceService.getException().printStackTrace());
currentPrice = new ReadOnlyDoubleWrapper(0);
currentPrice.bind(priceService.lastValueProperty());
startMonitoring();
}
public final void startMonitoring() {
priceService.restart();
}
public final void stopMonitoring() {
priceService.cancel();
}
public ReadOnlyDoubleProperty currentPriceProperty() {
return currentPrice.getReadOnlyProperty();
}
public final double getCurrentPrice() {
return currentPriceProperty().get();
}
private double getPriceData() {
// do actual retrieval work here...
}
}
(Code just typed in here without testing, but it should give you the idea.)
For the life of me, I cannot figure out why this program does not work in Java 7. I've run it with no problems in using Java 6, but as soon as I run it with Java 7, it doesn't work.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class HelloWorld implements ActionListener {
JButton button;
boolean state;
public HelloWorld(){
init();
state = false;
System.out.println("state - "+state);
while (true){
if (state == true){
System.out.println("Success");
}
}
}
private void init(){
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
button = new JButton("Button");
button.addActionListener(this);
frame.add(button);
frame.pack();
frame.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
JButton source = (JButton)e.getSource();
if (source == button){
state = !state;
System.out.println("state - "+state);
}
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
new HelloWorld();
}
}
Using Java 6, if I press the button, it will print out the phrase "Success" until I hit the button again. Using Java 7 registers that the button was pressed and the value of state was changed to true, but the phrase "Success" is never printed. What's going on?
Add volatile to the field declaration.
Without volatile, changes in the field are not guaranteed to be visible on other threads.
In particular, the JITter is free to believe that the field never changes on the main thread, allowing it to remove the if entirely.
When you show the JFrame
frame.setVisible(true);
The Java Show the window and stop the execution on this line.
You configured the window to exit on close:
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
This program will terminate after you close the window.
So the code after the init() call will never be executed.
Good evening,
In a test JSF 2.0 web app, I am trying to get the number of active sessions but there is a problem in the sessionDestroyed method of the HttpSessionListener.
Indeed, when a user logs in, the number of active session increases by 1, but when a user logs off, the same number remains as it is (no desincrementation happens) and the worse is that, when the same user logs in again (even though he unvalidated the session), the same number is incremented.
To put that in different words :
1- I log in, the active sessions number is incremented by 1.
2- I Logout (the session gets unvalidated)
3- I login again, the sessions number is incremented by 1. The display is = 2.
4- I repeat the operation, and the sessions number keeps being incremented, while there is only one user logged in.
So I thought that method sessionDestroyed is not properly called, or maybe effectively called after the session timeout which is a parameter in WEB.XML (mine is 60 minutes).
That is weird as this is a Session Listener and there is nothing wrong with my Class.
Does someone please have a clue?
package mybeans;
import entities.Users;
import java.io.*;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import jsf.util.JsfUtil;
/**
* Session Listener.
* #author TOTO
*/
#ManagedBean
public class SessionEar implements HttpSessionListener {
public String ctext;
File file = new File("sessionlog.csv");
BufferedWriter output = null;
public static int activesessions = 0;
public static long creationTime = 0;
public static int remTime = 0;
String separator = ",";
String headtext = "Session Creation Time" + separator + "Session Destruction Time" + separator + "User";
/**
*
* #return Remnant session time
*/
public static int getRemTime() {
return remTime;
}
/**
*
* #return Session creation time
*/
public static long getCreationTime() {
return creationTime;
}
/**
*
* #return System time
*/
private String getTime() {
return new Date(System.currentTimeMillis()).toString();
}
/**
*
* #return active sessions number
*/
public static int getActivesessions() {
return activesessions;
}
#Override
public void sessionCreated(HttpSessionEvent hse) {
// Insert value of remnant session time
remTime = hse.getSession().getMaxInactiveInterval();
// Insert value of Session creation time (in seconds)
creationTime = new Date(hse.getSession().getCreationTime()).getTime() / 1000;
if (hse.getSession().isNew()) {
activesessions++;
} // Increment the session number
System.out.println("Session Created at: " + getTime());
// We write into a file information about the session created
ctext = String.valueOf(new Date(hse.getSession().getCreationTime()) + separator);
String userstring = FacesContext.getCurrentInstance().getExternalContext().getRemoteUser();
// If the file does not exist, create it
try {
if (!file.exists()) {
file.createNewFile();
output = new BufferedWriter(new FileWriter(file.getName(), true));
// output.newLine();
output.write(headtext);
output.flush();
output.close();
}
output = new BufferedWriter(new FileWriter(file.getName(), true));
//output.newLine();
output.write(ctext + userstring);
output.flush();
output.close();
} catch (IOException ex) {
Logger.getLogger(SessionEar.class.getName()).log(Level.SEVERE, null, ex);
JsfUtil.addErrorMessage(ex, "Cannot append session Info to File");
}
System.out.println("Session File has been written to sessionlog.txt");
}
#Override
public void sessionDestroyed(HttpSessionEvent se) {
// Desincrement the active sessions number
activesessions--;
// Appen Infos about session destruction into CSV FILE
String stext = "\n" + new Date(se.getSession().getCreationTime()) + separator;
try {
if (!file.exists()) {
file.createNewFile();
output = new BufferedWriter(new FileWriter(file.getName(), true));
// output.newLine();
output.write(headtext);
output.flush();
output.close();
}
output = new BufferedWriter(new FileWriter(file.getName(), true));
// output.newLine();
output.write(stext);
output.flush();
output.close();
} catch (IOException ex) {
Logger.getLogger(SessionEar.class.getName()).log(Level.SEVERE, null, ex);
JsfUtil.addErrorMessage(ex, "Cannot append session Info to File");
}
}
} // END OF CLASS
I am retrieving the active sessions number this way:
<h:outputText id="sessionsfacet" value="#{UserBean.activeSessionsNumber}"/>
from another managedBean:
public String getActiveSessionsNumber() {
return String.valueOf(SessionEar.getActivesessions());
}
My logout method is as follow:
public String logout() {
HttpSession lsession = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
if (lsession != null) {
lsession.invalidate();
}
JsfUtil.addSuccessMessage("You are now logged out.");
return "Logout";
}
// end of logout
I'm not sure. This seems to work fine for a single visitor. But some things definitely doesn't look right in your HttpSessionListener.
#ManagedBean
public class SessionEar implements HttpSessionListener {
Why is it a #ManagedBean? It makes no sense, remove it. In Java EE 6 you'd use #WebListener instead.
BufferedWriter output = null;
This should definitely not be an instance variable. It's not threadsafe. Declare it methodlocal. For every HttpSessionListener implementation there's only one instance throughout the application's lifetime. When there are simultaneous session creations/destroys, then your output get overridden by another one while busy and your file would get corrupted.
public static long creationTime = 0;
public static int remTime = 0;
Those should also not be an instance variable. Every new session creation would override it and it would get reflected into the presentation of all other users. I.e. it is not threadsafe. Get rid of them and make use of #{session.creationTime} and #{session.maxInactiveInterval} in EL if you need to get it over there for some reason. Or just get it straight from the HttpSession instance within a HTTP request.
if (hse.getSession().isNew()) {
This is always true inside sessionCreated() method. This makes no sense. Remove it.
JsfUtil.addErrorMessage(ex, "Cannot append session Info to File");
I don't know what that method exactly is doing, but I just want to warn that there is no guarantee that the FacesContext is present in the thread when the session is about to be created or destroyed. It may take place in a non-JSF request. Or there may be no means of a HTTP request at all. So you risk NPE's because the FacesContext is null then.
Nonetheless, I created the following test snippet and it works fine for me. The #SessionScoped bean implicitly creates the session. The commandbutton invalidates the session. All methods are called as expected. How many times you also press the button in the same browser tab, the count is always 1.
<h:form>
<h:commandButton value="logout" action="#{bean.logout}" />
<h:outputText value="#{bean.sessionCount}" />
</h:form>
with
#ManagedBean
#SessionScoped
public class Bean implements Serializable {
public void logout() {
System.out.println("logout action invoked");
FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
}
public int getSessionCount() {
System.out.println("session count getter invoked");
return SessionCounter.getCount();
}
}
and
#WebListener
public class SessionCounter implements HttpSessionListener {
private static int count;
#Override
public void sessionCreated(HttpSessionEvent event) {
System.out.println("session created: " + event.getSession().getId());
count++;
}
#Override
public void sessionDestroyed(HttpSessionEvent event) {
System.out.println("session destroyed: " + event.getSession().getId());
count--;
}
public static int getCount() {
return count;
}
}
(note on Java EE 5 you need to register it as <listener> in web.xml the usual way)
<listener>
<listener-class>com.example.SessionCounter</listener-class>
</listener>
If the above example works for you, then your problem likely lies somewhere else. Perhaps you didn't register it as <listener> in web.xml at all and you're simply manually creating a new instance of the listener everytime inside some login method. Regardless, now you at least have a minimum kickoff example to build further on.
Something in a completely different direction - tomcat supports JMX. There is a JMX MBean that will tell you the number of active sessions. (If your container is not tomcat, it should still support JMX and provide some way to track that)
Is your public void sessionDestroyed(HttpSessionEvent se) { called ? I don't see why it won't increment. After the user calls session.invalidate() through logout, the session is destroyed, and for the next request a new one is created. This is normal behavior.
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.