Questions on events in a multi-class GUI
I have a GUI application that is constructed as follows:
1. Main Class - Actually creates the JFrame, contains main method, etc.
2. MenuBar Class - Constructor creates a new JMenuBar structure and populates it with various JMenus and JMenuItems. A new instance of this class is instantiated in the Main Class to be used in the setMenuBar() method.
3. ContentPane Class - Constructor creates a vertical JSplitPane. A new instance of this class is instantiated in the Main Class to be used in the setContentPane() method.
4. BottomPane Class - Constructor creates a JPanel and populates it with various stuff. A new instance of this class is instantiated in the Content Pane Class to be used as the bottom pane in the vertical JSplitPane.
5. TopPane Class - Constructor creates a horizontal JSplitPane and populates the left pane with a JScrollPane containing a JList. A new instance of this class is instantiated in the Content Pane Class to be used as the top pane in the vertical JSplitPane.
6. TabbedPane Class - Constructor creates a JTabbedPane. A new instance of this class is instantiated in the Top Pane Class to be used as the right pane in the horizontal JSplitPane.
7. DisplayPane Class - Constructor creates a JPanel. A new instance of this class is instantiated in the Tabbed Pane Class as the first tab. The user has the ability to click at points in this pane and a dialog box will pop up prompting the user for a string. Once the user enters something and clicks "OK", an instance of a custom Java2D component that I've created will be added to the DisplayPane where the user had clicked, with the string the user inputted being used as its name. The user can then drag the component around, enter a key combination to display all the names, etc.
8. Custom Java2D Component Class - Constructor creates my custom Java2D component. Instances of this are added to the Display Pane Class, as I have described.
Now, originally, I was going to ask "How do you work with events between these multiple classes?" but I have solved half of that problem myself with the following class:
9. Listener Class - A new instance of this class is declared in the constructor of the Main Class, and is thus passed down through the GUI hierachy via the constructors of the various classes. I then use the addActionListener() method on various components in the other classes, and then the Listener Class can capture an event using the getActionCommand() method to figure out what fired the event.
So that covers the "How do I capture events in multiple classes?" question. Now I'm left with "How do I affect changes on those classes based on events?"
For example: In my MenuBar class, I have a "Save" menu item. When this is clicked, I want to declare a new JFileChooser and then use the showSaveDialog() method, which throws up a dialog for saving a file. The problem is, the showSaveDialog() method takes a Component which is the parent frame. Obviously the Listener Class is not a frame. I want to use the Main Class as the parent frame. How would I do this sort of thing?
Another example: In my MenuBar class, I have a "New" menu item. For now, I want this to invoke a method in the DisplayPane Class that erases all of my custom Java2D components that have been made, thus giving the user a clean slate. How would I give my Listener Class access to that method?
A final example: Every time the user adds one of my custom Java2D components, I want that component's name to be added to the JList that is in my TopPane class. Vice versa with deleting a component: its name should be removed from the JList. How would I listen for new components being added? (A change listener on the pane? One on the ArrayList<> that contains all of the components? Something else?) And, of course, how would I give the Listener Class the ability to change the contents of the JList?
One idea I've come up with so far is to instantiate a new instance of each of my GUI classes in the Listener class, but that doesn't really make much sense. Wouldn't those be new instances that are totally separate from the instances the rest of my program is using? Another thought is to make the Listener Class an internal class inside the Main Class so that it can use the accessor methods of the GUI classes, but a.) I would like to avoid stuffing everything in one class and b.) this brings up the question of "How would I get an accessor method that is in a class that is two or three deep in the hierarchy?" (.getSomething().getSomethingInsideThat().getSomethingInsideTheInsideThing()?)
Help with answering any or all of my questions would be much appreciated.
Hrm. At the moment, for my first attempt, I'm doing something similar, it just strikes me as quite unwieldy.
Start of Listener class, with method for setting what it listens to. (I can't use a constructor for this because the MenuBar and the ContentPane take an instance of
this Listener class in through their constructors. You can't pass the Listener in through their constructors while simultaneously passing them in through this
Listener's constructor. That would be an endless cycle of failure. So I just instantiate an instance of this Listener class, then pass it in through the MenuBar and
ContentPane constructors when I instantiate instances of them, and then call this setListensTo() method.)
public class Listener implements ActionListener
private MenuBar menuBar;
private ContentPane contentPane;
public void setListensTo(MenuBar menuBar, ContentPane contentPane)
this.menuBar = menuBar;
this.contentPane = contentPane;
}The part of my actionPerformed() method that does some rudimentary saving, which I will make more complicated later:
else if (evt.getActionCommand() == "saveMenuItem")
JFileChooser fileChooser = new JFileChooser();
int returnVal = fileChooser.showSaveDialog(menuBar.getTopLevelAncestor());
if (returnVal == JFileChooser.APPROVE_OPTION)
File file = fileChooser.getSelectedFile();
ArrayList<Node> nodes = contentPaneClass.getTopPaneClass().getTabbedPane().getDisplayPane().getNodes();
try
BufferedWriter out = new BufferedWriter(new FileWriter(file));
for (int i = 0; i < nodes.size(); i++)
Node node = nodes.get(i);
out.write(node.getIndex() + "," + node.getXPos() + "," + node.getYPos() + "," + node.getName());
out.newLine();
out.close();
catch (IOException e)
//To be added
}That part that seems unwieldy is the
ArrayList<Node> nodes = contentPaneClass.getTopPaneClass().getTabbedPane().getDisplayPane().getNodes();The reason I'm using a separate Listener class is because if I put, say, the actions for the MenuBar in the MenuBar class, and then want to save stuff in the JPanel
at the bottom of the hierachy, I would have to go up from the MenuBar into the JFrame, and then back down the hierachy to the JPanel, and vice versa. Kind of like
walking up a hill and then down the other side. I imagine this would be even more unwieldy than what I'm doing now.
On the plus side, I am making progress, so thanks all for the help so far!
Similar Messages
-
GUI, JFrame, JPanel, ActionListener, simple multi-class applications
My assignment calls for:
"Create a Frame class"
"Create a Panel class which implements ActionListener. Add JLabels, JTextFields, JButtons to the panel"
most of this is pretty straight forward right out of GUI examples from my textbook
but I don't have much experience with running multi-class programs, and this one is a bit more complicated b.c we have to use implement and possibly extend modifiers, which are new to me
any thoughts?
Edited by: infinitelyLooping on Sep 16, 2008 11:52 AMimport javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class TestX extends JFrame {
MyPanel pnl;
public TestX() {
super();
pnl = new MyPanel();
getContentPane().add(pnl);
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
setVisible(true);
class MyPanel extends JPanel implements ActionListener
private JLabel lbl;
private JTextField txt;
private JButton btn;
public MyPanel() {
super();
lbl = new JLabel();
txt = new JTextField();
btn = new JButton("btn");
btn.addActionListener(this);
add(lbl);
add(txt);
add(btn);
public void actionPerformed(ActionEvent e) {
txt.setText("Clicked");
} -
Having an issue with event handling - sql database & java gui
HI all, have posted this on another forum but I think this is the correct one to post on. I am trying to construct this hybrid of java and mysql. the data comes from a mysql database and I want it to display in the gui. this I have achieved thus far. However I have buttons that sort by surname, first name, ID tag etc....I need event handlers for these buttons but am quite unsure as to how to do it. any help would be much appreciated. Thanks in advance.
/* Student Contact Database GUI
* Phillip Wells
import java.awt.BorderLayout;
// imports java class. All import class statements tell the compiler to use a class that is defined in the Java API.
// Borderlayout is a layout manager that assists GUI layout.
import javax.swing.*; // imports java class. Swing enables the use of a GUI.
import javax.swing.JOptionPane; // imports java class. JOptionPane displays messages in a dialog box as opposed to a console window.
import javax.swing.JPanel; // imports java class. A component of a GUI.
import javax.swing.JFrame; // imports java class. A component of a GUI.
import javax.swing.JButton; // imports java class. A component of a GUI.
import javax.swing.JScrollPane; // imports java class. A component of a GUI.
import javax.swing.JTable; // imports java class. A component of a GUI.
import java.awt.*; // imports java class. Similar to Swing but with different components and functions.
import java.awt.event.*; // imports java class. Deals with events.
import java.awt.event.ActionEvent; // imports java class. Deals with events.
import java.awt.event.ActionListener; // imports java class. Deals with events.
import java.sql.*; // imports java class. Provides API for accessing and processing data stored in a data source.
import java.util.*; // imports java class. Contains miscellaneous utility classes such as strings.
public class studentContact extends JFrame { // public class declaration. The �public� statement enables class availability to other java elements.
private JPanel jContentPane; // initialises content pane
private JButton snam, id, fname, exit; // initialises Jbuttons
String firstname = "firstname"; //initialises String firstname
String secondname = "secondname"; //initialises String
public studentContact() {
Vector columnNames = new Vector(); // creates new vector object. Vectors are arrays that are expandable.
Vector data = new Vector();
initialize();
try {
// Connect to the Database
String driver = "com.mysql.jdbc.Driver"; // connect to JDBC driver
String url = "jdbc:mysql://localhost/Studentprofiles"; //location of Database
String userid = "root"; //user logon information for MySQL server
String password = ""; //logon password for above
Class.forName(driver); //reference to JDBC connector
Connection connection = DriverManager.getConnection(url, userid,
password); // initiates connection
// Read data from a table
String sql = "Select * from studentprofile order by "+ firstname;
//SQL query sent to database, orders results by firstname.
Statement stmt = connection.createStatement
(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
//statement to create connection.
//Scroll sensitive allows movement forth and back through results.
//Concur updatable allows updating of database.
ResultSet rs = stmt.executeQuery(sql); // executes SQL query stated above and sets the results in a table
ResultSetMetaData md = rs.getMetaData(); // used to get the properties of the columns in a ResultSet object.
int columns = md.getColumnCount(); //
for (int i = 1; i <= columns; i++) {
columnNames.addElement(md.getColumnName(i)); // Get column names
while (rs.next()) {
Vector row = new Vector(columns); // vectors data from table
for (int i = 1; i <= columns; i++) {
row.addElement(rs.getObject(i)); // Get row data
data.addElement(row); // adds row data
rs.close();
stmt.close();
} catch (Exception e) { // catches exceptions
System.out.println(e); // prints exception message
JTable table = new JTable(data, columnNames) { //constructs JTable
public Class getColumnClass(int column) {
for (int row = 0; row < getRowCount(); row++) {
Object o = getValueAt(row, column);
if (o != null) {
return o.getClass();
return Object.class;
JScrollPane scrollPane = new JScrollPane( table ); // constructs scrollpane 'table'
getContentPane().add(new JScrollPane(table), BorderLayout.SOUTH); //adds table to a scrollpane
private void initialize() {
this.setContentPane(getJContentPane());
this.setTitle("Student Contact Database"); // sets title of table
ButtonListener b1 = new ButtonListener(); // constructs button listener
snam = new JButton ("Sort by surname"); // constructs Jbutton
snam.addActionListener(b1); // adds action listener
jContentPane.add(snam); //adds button to pane
id = new JButton ("Sort by ID"); // constructs Jbutton
id.addActionListener(b1); // adds action listener
jContentPane.add(id); //adds button to pane
fname = new JButton ("Sort by first name"); // constructs Jbutton
fname.addActionListener(b1); // adds action listener
jContentPane.add(fname); //adds button to pane
exit = new JButton ("Exit"); // constructs Jbutton
exit.addActionListener(b1); // adds action listener
jContentPane.add(exit); //adds button to pane
private JPanel getJContentPane() {
if (jContentPane == null) {
jContentPane = new JPanel(); // constructs new panel
jContentPane.setLayout(new FlowLayout()); // sets new layout manager
return jContentPane; // returns Jcontentpane
private class ButtonListener implements ActionListener { // create inner class button listener that uses action listener
public void actionPerformed (ActionEvent e)
if (e.getSource () == exit) // adds listener to button exit.
System.exit(0); // exits the GUI
if (e.getSource () == snam)
if (e.getSource () == id)
if (e.getSource () == fname)
public static void main(String[] args) { // declaration of main method
studentContact frame = new studentContact(); // constructs new frame
frame.setDefaultCloseOperation(EXIT_ON_CLOSE); //exits frame on closing
frame.setSize(600, 300); // set size of frame
frame.setVisible(true); // displays frame
}OK, so you've got this code here:
private class ButtonListener implements ActionListener {
public void actionPerformed (ActionEvent e) {
if (e.getSource () == exit) {
System.exit(0); // exits the GUI
if (e.getSource () == snam) {
if (e.getSource () == id) {
}Perfect fine way to do this; although I think creating anonymous would be a bit cleaner:
snam.addActionListener(new actionListener() {
public void actionPerformed(ActionEvent ae) {
});But I think that the real question you have is "what do I put for logic when the JButtons are hit?", right?
I would answer that you want to dynamically build your SQL statement changing your ordering based on the button.
So you'd have a method that builds the SQL based on what you pass in - so it takes one argument perhaps?
private static final int NAME = 1;
ID = 2;
/* ... some code ... */
snam.addActionListener(new actionListener() {
public void actionPerformed(ActionEvent ae) {
buildSQL(NAME);
/* ... some code ... */
private void buildSQL(int type) {
if ( type == NAME ) {
/* ... build SQL by name ... */
else if ( type == ID ) {
/* ... build SQL by id ... */
}That kind of thing.
Or you might choose to have several build methods with no parameter type; each building the SQL differently, and calling whichever one you need. I did not read your entire pgm, so I don't know how you'd want to organize it. You need to ask more specific questions at that point.
~Bill -
How can I (neatly) control mouse click events in a multi-dimensional array?
Hello everyone!
I have a question regarding the use of mouse clicks events in a multi-dimensional array (or a "2D" array as we refer to them in Java and C++).
Background
I have an array of objects each with a corresponding mouse click event. Each object is stored at a location ranging from [0][0] to [5][8] (hence a 9 x 6 grid) and has the specific column and row number associated with it as well (i.e. tile [2][4] has a row number of 2 and a column number of 4, even though it is on the third row, fifth column). Upon each mouse click, the tile that is selected is stored in a temporary array. The array is cleared if a tile is clicked that does not share a column or row value equal to, minus or plus 1 with the currently targeted tile (i.e. clicking tile [1][1] will clear the array if there aren't any tiles stored that have the row/column number
[0][0], [0][1], [0][2],
[1][0], [1][1], [1][2],
[2][0], [2][1], [2][2]
or any contiguous column/row with another tile stored in the array, meaning that the newly clicked tile only needs to be sharing a border with one of the tiles in the temp array but not necessarily with the last tile stored).
Question
What is a clean, tidy way of programming this in AS3? Here are a couple portions of my code (although the mouse click event isn't finished/working correctly):
public function tileClick(e:MouseEvent):void
var tile:Object = e.currentTarget;
tileSelect.push(uint(tile.currentFrameLabel));
selectArr.push(tile);
if (tile.select.visible == false)
tile.select.visible = true;
else
tile.select.visible = false;
for (var i:uint = 0; i < selectArr.length; i++)
if ((tile.rowN == selectArr[i].rowN - 1) ||
(tile.rowN == selectArr[i].rowN) ||
(tile.rowN == selectArr[i].rowN + 1))
if ((tile.colN == selectArr[i].colN - 1) ||
(tile.colN == selectArr[i].colN) ||
(tile.colN == selectArr[i].colN + 1))
trace("jackpot!" + i);
else
for (var ii:uint = 0; ii < 1; ii++)
for (var iii:uint = 0; iii < selectArr.length; iii++)
selectArr[iii].select.visible = false;
selectArr = [];
trace("Err!");Andrei1,
So are you saying that if I, rather than assigning a uint to the column and row number for each tile, just assigned a string to each one in the form "#_#" then I could actually just assign the "adjacent" array directly to it instead of using a generic object to hold those values? In this case, my click event would simply check the indexes, one at a time, of all tiles currently stored in my "selectArr" array against the column/row string in the currently selected tile. Am I correct so far? If I am then let's say that "selectArr" is currently holding five tile coordinates (the user has clicked on five adjacent tiles thus far) and a sixth one is being evaluated now:
Current "selectArr" values:
1_0
1_1, 2_1, 3_1
2_2
New tile clicked:
1_0
1_1, 2_1, 3_1
2_2
2_3
Coordinate search:
1_-1
0_0, 1_0, 2_0, 3_0
0_1, 1_1, 2_1, 3_1, 4_1
1_2, 2_2, 3_2
2_3
Essentially what is happening here is that the new tile is checking all four coordinates/indexes belonging to each of the five tiles stored in the "selectArr" array as it tries to find a match for one of its own (which it does for the tile at coordinate 2_2). Thus the new tile at coordinate 2_3 would be marked as valid and added to the "selectArr" array as we wait for the next tile to be clicked and validated. Is this correct? -
Event handling in seperate class
hello... i have a gui w/ a series of combo boxes, text fields, etc. (call this the GUI file)
upon pressing a button, i need to run a series of event handling that will use info from many of these components
i would like to create a separate java file for the button event handling, but need this file to have access to many componets in the GUI file - does anyone know a nice way to do this?i'm not quite sure how to do that... in my GUI class,
I construct the actuall gui within the constructor..
then i have a simple driver that creates an instance
of class GUI and calls the constructor... how can I
pass a reference of the GUI to the handler in that
scenario??it would be better if you post your code. Some people like me can't just imagine. -
Event triggering by abap class & ISR
hi gurus
1 ) can i able to see the event triggering by abap class in SWEL ? ,
2) in custom ISR scenario , new form scenario has been created by our functional consultant , and asking me to trigger a workflow for approval , when employee fills that particular ISR FORM , workflow should start and to go his HR administrator , when HR administrator double click on workitem he should get the ISR form in display mode & also with some descpition text is to be added in the screen (like user decision description ) with approval button ..... my question is how to trigger a event from in form scenario ? , how to bring the FORM screen to display mode to the HR administrator ?
regards
suryaHi Surya
The BO for ISR forms is BUS7051 - Notification. Turn on the trace via SWELS and create a PCR/ISR form and you should see the events being triggered in SWEL.
Good Luck
Ravi -
Getting class Gui's to show up in other class Gui's
Can you, and if so how do you make them show up, set classes that are extended (say, a JTextField class) to show up in another class (like a panel or Frame). I can't seem to get them to show up. I can't find any relavent topics with a search.
Does my entire GUI have to be made of all methods from the same class????? Help anyone!import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class GUI // in my case I exetended Observable (because I needed to) instead of extends JFrame
public GUI ()
{ JFrame frame = new JFrame();
setTitle ("Title");
addWindowListener (new WindowAdapter ()
public void windowClosing (WindowEvent e)
dispose ();
System.exit (0);
// JPanel p = getMyStuff ()
// use this instead (or a new object of getMyStuff)
frame.getContentPane ().add(new getMyStuff());;
// DON'T pack ();
show ();
public static void main (String [] args)
new GUI ();
class getMyStuff extends JPanel
// you can use anything like this as long as its a component (for adding into other things) - havnen't been able to add an extended Observable yet (I guess I'll have to use a private for each class Observable myObservers = new Observable();
public getMyStuff ()
//JPanel p = new JPanel (); // not needed now
add (new JLabel ("This is a label"));
add (new JTextField (15));
add (new JButton ("Button"));
add (new JTextArea ("Chili is good... mmm"));
add (new JPasswordField (15));
} -
Error occured in invoking event "contextInitialized()" on listener class co
Hi All,
I am working on JSF 1.2 on SAP NetWeaver CE. I am able to execute sample JSF application successfully when NO java program is written in the application. When I write a java program inside the JSF application...I am getting following error. Please let me know how to proceed on this:
"Application error occurred during the request procession."
Error occured in invoking event "contextInitialized()" on listener class com.sun.faces.config.ConfigureListener.
Details:
java.lang.UnsupportedClassVersionError: Bad version number in .class file
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:654)
at com.sap.engine.boot.loader.ResourceMultiParentClassLoader.loadClassLocal(ResourceMultiParentClassLoader.java:198)
at com.sap.engine.boot.loader.MultiParentClassLoader.findClassInLoaderGraph(MultiParentClassLoader.java:302)
at com.sap.engine.boot.loader.MultiParentClassLoader.loadClass(MultiParentClassLoader.java:256)
at com.sap.engine.boot.loader.MultiParentClassLoader.loadClass(MultiParentClassLoader.java:228)
at com.sun.faces.config.ManagedBeanFactoryImpl.getManagedBeanClass(ManagedBeanFactoryImpl.java:227)
at com.sun.faces.config.ManagedBeanFactoryImpl.scanForAnnotations(ManagedBeanFactoryImpl.java:1130)
at com.sun.faces.config.ManagedBeanFactoryImpl.<init>(ManagedBeanFactoryImpl.java:156)
at com.sun.faces.config.ConfigureListener.configure(ConfigureListener.java:926)
at com.sun.faces.config.ConfigureListener.configure(ConfigureListener.java:507)
at com.sun.faces.config.ConfigureListener.contextInitialized(ConfigureListener.java:402)
at com.sap.engine.services.servlets_jsp.server.application.WebEvents.contextInitialized(WebEvents.java:74)
at com.sap.engine.services.servlets_jsp.server.deploy.ApplicationThreadInitializer.run(ApplicationThreadInitializer.java:198)
at com.sap.engine.core.thread.impl3.ActionObject.run(ActionObject.java:37)
at java.security.AccessController.doPrivileged(Native Method)
at com.sap.engine.core.thread.impl3.SingleThread.execute(SingleThread.java:152)
at com.sap.engine.core.thread.impl3.SingleThread.run(SingleThread.java:247)
Rgds,
PathanPathan wrote:
java.lang.UnsupportedClassVersionError: Bad version number in .class fileThe Java version of the Java compiler used is newer than the Java version of the Java runtime used.
E.g. compiling with JDK 1.6 and running with JRE 1.5 would cause this error. -
Event triggering from a class to parent
Hi,
I am trying to write a custom class for image loading.
public function imageLoader(url:String, mc:MovieClip):void {
loader = new Loader();
loader.load(new URLRequest(url));
mc.addChild(loader);
loader.contentLoaderInfo.addEventListener(Event.INIT, initListener);
loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, progressListener);
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loadListener);
public function initListener(e:Event):void {
public function progressListener(e:ProgressEvent):void {
public function loadListener(e:Event):void {
I ll get the events in these listeners in the loadImage class. But i want to trigger a function in the calling class or root or stage, when these loader events are fired.
How this can be done?
Regards,
Sreelashthe ImageLoader class should extend EventDispatcher
you cna then redispatch the events wihtin the ImageLoader class
e.g.
public function initListener(e:Event):void {
dispatchEvent(e);
then in the parent class you will have a reference to the ImageLoader class and you can add event listeners there
e.g.
var imageLoader:ImageLoader = new ImageLoader();
imageLoader.addEventListener(Event.INIT, somefunction);
imageLoader.load("image", this);
or something alone these lines depending on how you want to structure things -
Use of events and interface in class
Dear All,
Could you please explain why we use events and interface in class.
Also please tell me the use of TRY and ENDTRY.
Regards,
AmarEvents may be a way of communication b/w classes. Imagine you want to call certain code from one class, you would need for that public method, but you don't want to expose it to external user. So you may use events for that. Also events are used to notify that certain state of class has changed (tiggering event). Then all handlers of this event executes and react accordingly.
Interfaces are a way of provide a service to class which implements it. Imagine that you have class office and hotel and gas station . They don't seems to have something in common. However, there can be some external energy provider which will be an interface. Each class which want to have a lease with this energy provided can implement it (the implementation can differ in some way), so he can provided energy to different classes. This way you will achieve polimorphism (meaning you call one interface method, but code behind it differs from class to class).
Interfaces are also means of multiple inheritance. One class can implement several service (interfaces). In contrary it can oly inherit from one class.
Try endtry are just new way of handling exceptions .
Try to search a litte bit you will find lots of info on the above.
Regards
Marcin -
Dispatching a simple event from classB to ClassA
Hi,
I have read at multiple places tutorials/explanations on the EventDispatcher use in AS3 and that confuses me a lot. I would appreciate a lot if somebody could show me in the simple exemple below how I should do to just send a simple message from a ClassB to a Class A. In the exemple below that I made, I have classA that calls classB to send a message that ClassA then gets. Of course, I simplified to the minimum the 2 classes to allow focusing on the problem. Currently, the exemple does NOT work, i.e. the line "trace ("message was received!");" is not executed.
I saw in several exemples on the web that some put the addEventListener on the EventDispatcher object. I do not understand the logic behind this, I would put the addEventListener on the objects that will receive the message.
I wonder also why can't I just put an addEventlistener at the ClassA constructor "addEventListener("hello", receivedHello);" and then send a dispatchEvent from classB. I tried that as well but it does not work.
package {
import flash.display.MovieClip;
import flash.events.Event;
public dynamic class ClassA extends MovieClip{
public function ClassA(){
ClassB.getClassB().registerUser(this);
ClassB.getClassB().sendMessage();
public function receivedHello(e:Event){
trace ("message was received!");
package{
import flash.events.Event;
import flash.events.EventDispatcher;
class ClassB {
public var sender:EventDispatcher;
// constructor
public function ClassB() {
sender= new EventDispatcher();
// function getClassB() to be sure only one instance of this class is running
public static function getClassB():ClassB {
if (ClassB._instance == null) {
ClassB._instance = new ClassB();
return ClassB._instance;
public function registerUser(user:Object){
user.addEventListener("hello", user.receivedHello);
public function sendMessage(): void {
sender.dispatchEvent(new Event("hello"));
Thanks so much in advance for your help
Pieterpackage {
import flash.display.MovieClip;
public dynamic class ClassA extends MovieClip{
public function ClassA(){
addEventListener("customEvent",f);
function f(e:Event){
trace("event received");
package{
import ClassA;
import flash.events.Event;
import flash.events.EventDispatcher;
class ClassB {
// constructor
public function ClassB() {
var a:ClassA = new ClassA();
a.dispatchEvent(new Event("customEvent")) -
Revision: 8864
Author: [email protected]
Date: 2009-07-28 11:31:14 -0700 (Tue, 28 Jul 2009)
Log Message:
Fix for ASDoc @event tag assumes the class is in flash.events package
Bugs: SDK-22275
QE Notes: None.
Doc Notes: None.
tests: checkintests, asdoc
Ticket Links:
http://bugs.adobe.com/jira/browse/SDK-22275
Modified Paths:
flex/sdk/trunk/modules/compiler/src/java/flex2/compiler/asdoc/TopLevelClassesGenerator.ja vaerror dateField not selecion date 27/11/2002 ?
This is bug flex 3 ?
thanks -
Design question about when to use inner classes for models
This is a general design question about when to use inner classes or separate classes when dealing with table models and such. Typically I'd want to have everything related to a table within one classes, but looking at some tutorials that teach how to add a button to a table I'm finding that you have to implement quite a sophisticated tablemodel which, if nothing else, is somewhat unweildy to put as an inner class.
The tutorial I'm following in particular is this one:
http://www.devx.com/getHelpOn/10MinuteSolution/20425
I was just wondering if somebody can give me their personal opinion as to when they would place that abstracttablemodel into a separate class and when they would just have it as an inner class. I guess re-usability is one consideration, but just wanted to get some good design suggestions.It's funny that you mention that because I was comparing how the example I linked to above creates a usable button in the table and how you implemented it in another thread where you used a ButtonColumn object. I was trying to compare both implementations, but being a newbie at this, they seemed entirely different from each other. The way I understand it with the example above is that it creates a TableRenderer which should be able to render any component object, then it sets the defaultRenderer to the default and JButton.Class' renderer to that custom renderer. I don't totally understand your design in the thread
http://forum.java.sun.com/thread.jspa?forumID=57&threadID=680674
quite yet, but it's implemented in quite a bit different way. Like I was saying the buttonClass that you created seem to be creating an object of which function I don't quite see. It looks more like a method, but I'm still trying to see how you did it, since it obviously worked.
Man adding a button to a table is much more difficult than I imagined.
Message was edited by:
deadseasquirrels -
How to tackle the dataflow problem when Value Change event always triggers after another GUI event
We know that Value change event always triggers after another GUI event. Eg, the user modifies string control, the user clicks on a boolean control. Then event boolean clicked is triggered before event string control value change.
Now suppose somehow the GUI event that must happen to subsequently trigger the Value change event can potentially affect the data that Value change event is supposed to work on. How can we tackle this problem ?
For example, in a mockup application that the grand purpose is to have user entered values in a textbox logged to a file (no missing information is accepted, and there is a boolean to determine how the information is logged).
There are 2 controls, boolean A when clicked (mouse down) will load random number in text box B. Text box B is designed with event structure VALUE change which saves whatever values user enters into text box B to a log file.
There are 3 problems when instead of clicking anywhere on the front panel after modifying text box B, the user ends up clicking on boolean control A.
1. Event mouse down on Boolean control A will execute first, modifying text box B content before the user entered values in B get saved.
2. The value of boolean A can potentially affect how textbox B is loggged.
3. The value of boolean A affects how the file is logged and this is indeterminate. Somehow when running this VI with no Highlighting, the textbox B Value change event executes -before- boolean A value is updated (F to T). When running this VI with Highlighting, the boolean A value is updated (F to T) (because we click on it) -before- textbox B value change event occurs. Why is it like this ?
Now the situation I made up seems non-sense, but I believe it resembles one way or another a problem that you might run into. How would you solve this problem elegantly ?
You can set the string control to "update while typing".
Are you sure appending the log to itself is reasonable? Wouldn't it grow without bounds if the users keeps entering strings or pressing the ingore button?
Why isn't the "constant" a diagram constant instead of a control. Is the user allowed to change it?
To reset just write empty strings or a false to local variables of the controls (renit to defaults" seems a bit heavy handed).
All you probably need is a single event case for "ignore:value change" and "String" value changed", no need for the local variable..
Also add a stop button and an event for it.
You don't need the timeout event.
-
Event handling in custom Non-GUI components
I have a class which needs to fire events to outside. These events maybe captured by several objects in outside world. How can I achieve this? In so many places I read, they always refer to AWT and Swing whereas my objects don't have any dependency to GUI.
I simply need to fire an event from an object, and capture that event from other objects by registering event handlers.
I have experience in .Net programming with Events and Delegates (function pointers), but cannot find something like that in Java. All it offers is various kinds of GUI related Listeners where I can't find a proper help resource using them in Non-GUI components.ravinsp wrote:
I have a class which needs to fire events to outside. These events maybe captured by several objects in outside world. How can I achieve this? In so many places I read, they always refer to AWT and Swing whereas my objects don't have any dependency to GUI.
I simply need to fire an event from an object, and capture that event from other objects by registering event handlers.
I have experience in .Net programming with Events and Delegates (function pointers), but cannot find something like that in Java. All it offers is various kinds of GUI related Listeners where I can't find a proper help resource using them in Non-GUI components.If you want to make your own Listener make your Listener. Create an event class that encapsulates the event as you want, create a listener interface that has a method like handleMyEvent(MyEvent me) and then add addMyEventListener, removeMyEventListener methods to your original class. Add a List<MyEvent> to your original class and add the listeners to it and then when events happen
MyEvent someEvent = new MyEvent();
for(MyEventListener mel : eventlisteners)
mel.handleMyEvent(someEvent);
Maybe you are looking for
-
Changing the file name of photo in Finder.
I need to change the file name of my photos. I have changed the settings so that they show on iPhoto as 001, 002 etc - but I need this information to also be set in Finder. Is this possible? NikiKL
-
Need blank form fields when page spawned
Hi all, I have a fillable form that has buttons at the top of every page to for the user to duplicate the page in case more information needs to be entered. Here is the javascript I'm using, courtesy of George Johnson: // Get a template object from
-
Do I have to purchase the Mac OS X v10.6.6 in order to update my software. My software version is currently 10.5.8. I have updated my iphone 4 to the IOS6 version however my macbook is still at 10.5.8 version therefore i am not able to update my I
-
Getting a invalid password for e-mail
i put in my pass word to activate my e-mail on my black berry curve 9310 and it keeps telling my pass word is invalid and won't valate my e-mail on my phone
-
Multiple libraries with Apple TV?
I have an iTunes library on my iMac and an iTunes library on an external drive, the idea was to keep my music on my iMac and keep my movies on my external drive, therefore saving some space on my iMac hard drive. This seems to be working okay, but th