Reference Flex Stage From AS Class

I have an AS2 Class that I am converting to AS3. There are
several functions which used to reference _root to get a list of
objects from the main "stage". I am having trouble finding a
reference from the class to the main application.
Specifically, this is what I would like to do:
In the AS3 class, I want to reference the main application's
stage display list and parse through it. For example, if I were
using the following code from
http://livedocs.macromedia.com/flex/2/docs/wwhelp/wwhimpl/common/html/wwhelp.htm?context=L iveDocs_Parts&file=00001853.html
in an AS3 class, and I wanted to parse through the DisplayList of
the main application's stage objects, how could I reference the
main application stage without having to pass the objects through
from the main application?
The following code works if it is part of the main
application, but using 'this' in the function call doesn't work,
nor does the use of 'stage' if this same code is moved to and AS
class and imported into the main application.
function traceDisplayList(container:DisplayObjectContainer,
indentString:String = ""):void {
var child:DisplayObject;
for (var i:uint=0; i < container.numChildren; i++) {
child = container.getChildAt(i);
trace (indentString, child, child.name);
if (container.getChildAt(i) is DisplayObjectContainer) {
traceDisplayList(DisplayObjectContainer(child), indentString
+ " ")
traceDisplayList(this);
Any suggestoins? Am I just approaching this the wrong way?
Thank you.

Thank you Peter. This was exactly what I needed. To make it
work properly I just had to:
import mx.core.Application
var tempObj:Object = Application.application;
traceDisplayList(tempObj);
It works great! Thank you.

Similar Messages

  • How would you reference respective video from diff class?

    Hi. I wanted to get a couple of points of view (if you're willing to look ) on how others would do this because Im not sure where to even start.
    I have a buttons class that puts 9 pictures on the stage and each one represents a different movie and leads to that movie when clicked (or will lead there once I figure out how to reference it to the specific movie).
    I have 9 movies referenced through XML. And I am using flvPlayer. Currenly I can only have one movie loading. I am not sure how to get each one to play upon click of the respective btn.
    Here is some of the code I think is pertinent if figuring how to go about this:
    ProjectOneButtons class
    //I have each picture loaded through an array and each button is waiting for the right code through a Switch statement:
    public function onButtonClick(e:MouseEvent):void {
         var releventImageAray:Array = this["rowOfImages" + MovieClip(e.currentTarget).row];
         var imageWanted:String = relaventImageArray[MovieClip(e.currentTarget).column];
         switch (imageWanted) {
              case "Video1" :
                   //Have not figured out the specific video code in class below
                   //This switch statement continues for the rest of the buttons.
                   //this code works but it just loads one movie and so I don't think this is what I need.
                   projectOneVideos = new projectOneVideos();
                   addChild(projectOneVideos);
                   projectOneVideos.x = 0;
                   projectOneVideos.y = 0;
    Here is the ProjectOneVideos class where the videos are loaded and played:
    package asFiles.projectOne{
         //import statments taken out for post
         public class ProjectOneVideos extends Sprite {
              public var videoX:Number;
              public var videoY:Number;
              public var projectOneVideos:XMLList;
              public var projectOneTotal:Number;
              public var projectOneXML:XML;
              public var xmlLoader:URLLoader;
              public var player:FLVPlayback;
              public var playBtn:VideoPlayBtn;
              public var pauseBtn:VideoPauseBtn;
              public var videoContainer:MovieClip = new MovieClip;
              public function ProjectOneVideos() {
                   xmlLoader = new URLLoader();
                   xmlLoader.load(new URLRequest("projectOneVideos.xml"));
                   xmlLoader.addEventListener(Event.COMPLETE, processXML);
              public function processXML(e:Event):void {
                   projectOneXML = new XML(e.target.data);
                   projectOneVideos = projectOneXML.VIDEO;
                   projectOneTotal = projectOneXML.length();
                   makePlayer();
                   addButtons();
              public function makePlayer():void {
                   player = new FLVPlayback();
                   player.skinBackgroundColor = 0x47ABCB;
                   player.skinBackgroundAlpha = .85;
                   player.x = 40.3;
                   player.y = 220;
                   player.width = 1200;
                   player.height = 594.2;
                   videoContainer.addChild(player);
                   player.addEventListener("complete", backToVideoMenu);
              public function addButtons():void {
                   trace("addButtons initiated");
                   playBtn = new VideoPlayBtn();
                   videoContainer.addChild(playBtn);
                   playBtn.x = 625.6;
                   playBtn.y = 930;
                   pauseBtn = new VideoPauseBtn();
                   videoContainer.addChild(pauseBtn);
                   pauseBtn.x = 625.6;
                   pauseBtn.y = 930;
                   pauseBtn.visible = false;
                   addChild(videoContainer);
                   videoContainer.x = 0;
                   videoContainer.y = 0;
                   playBtn.addEventListener(MouseEvent.CLICK, playVideo);
                   pauseBtn.addEventListener(MouseEvent.CLICK, playVideo);
              public function playVideo(event:MouseEvent):void {
              // this is where I have the video referenced to play.
                   trace("play/pause button clicked");
                   if (player.playing || player.paused) {
                        if (player.paused) {
                             player.play();
                        } else {
                             player.pause();
                        playBtn.visible = player.paused;
                        pauseBtn.visible = ! player.paused;
                   } else if (player.stopped) {
                        player.play();
                        playBtn.visible = false;
                        pauseBtn.visible = true;
                   } else {
                                    //this will obviously not work because then its just this one movie referenced
                        player.play("videos/projectOneVideos/videoOne.f4v", 0, false);
                        pauseBtn.visible = true;
                        playBtn.visible = false;
    The reason I included a bunch of code is to show that there is a play/pause button that is supposed to play the movie. But the thing is I only have the one movie referenced and I am not sure how to have it variable as to which movie is played and make it depend on the button that is clicked from the button class above.
    thanks for any input you can give!!! 
    Note: All of this code works as it is and I am getting no errors.

    Ok, how about this:
    After reviewing my code again, this is what I find.
    I process the xml and then never use it when playing the video. To play the video I had just put the path straight to the video and not even used the xml. In the xml.
    So I guess my question is how to I refer to the xml to load the video and then when dealing with the buttons lead to the right video from the xml.
    kglad: Now I think I see why you were saying define a method of the ProjectOneVideos class that accepts a path/name string to the load target.
    I think the code I need to change is:
         if (player.playing || player.paused) {
                        if (player.paused) {
                             player.play();
                        } else {
                             player.pause();
                        playBtn.visible = player.paused;
                        pauseBtn.visible = ! player.paused;
                   } else if (player.stopped) {
                        player.play();
                        playBtn.visible = false;
                        pauseBtn.visible = true;
                   } else {
               //this is the part that needs to be changed to recognize from the xml
                        player.play("videos/projectOneVideos/videoOne.f4v", 0, false);
                        pauseBtn.visible = true;
                        playBtn.visible = false;
    But then I have to be able to pull the right video when I hit the button.
    So, what tools should I be using?

  • How do I reference a MovieClip from a class

    Hi. Trying to learn AS3 and having a hard time ; (
    I'm working on a game. I have a Ship class that uses addChild
    to add a linked Bullet MovieClip to the stage. The Bullet MC is
    linked to the class below. I've got it working so it moves up the
    screen, but now I need to build a hitTest, however I cant get
    access to a movie clip I've placed on the stage, "enemyDisplay_mc".
    How do I reference this MC? In AS2 I would just do a _root.
    Thanks!
    package {
    import flash.display.*;
    import flash.events.Event;
    public class Weapons extends MovieClip {
    private var _thisWeaponMC:MovieClip;
    private var _enemyHit:DisplayObject;
    private var _speed:Number;
    public function Weapons () {
    this.addEventListener (Event.ADDED,Initialize);
    private function Initialize (event:Event):void {
    //trace ("Weapons");
    _thisWeaponMC =
    MovieClip(this.parent.getChildByName(this.name));
    trace ("_thisWeaponMC: " + _thisWeaponMC);
    _thisParent = event.currentTarget.parent;
    trace ("_thisParent: " + _thisParent);
    _enemyHit = this.parent.getChildByName("enemyDisplay_mc");
    trace ("_enemyHit: " + _enemyHit);
    _speed=20;
    this.addEventListener (Event.ENTER_FRAME,moveShip);
    private function moveShip (event:Event):void {
    this.y-= _speed;
    }

    This code is called from my Ship class.
    The Ship class is the Base class of the ship movie clip.
    VulcanShot is the linkage class name of the bullet movie,
    it's base class is Weapons.
    Thanks!

  • Accessing display object on the stage from another class

    I've googled this to no avail, I've only found how to manipulate the stage itself and not a display object on it, and I'm noob enough to not be able to figure it out from there. :/
    I have a movie clip on the main timeline with instance name displayName. I created a button that should change what frame displayName goes to (in order to...did you guess it?! diplay the Name of the button. Awesome. )
    So I am trying to write the code in a reusable fashion and have the buttons all linked to a class called GeoPuzzle. Inside GeoPuzzle I instantiate a touch event and run the code. However, the function has to be able to change displayName in the main part of the timeline and, of course, the compiler says displayName doesn't exist because I'm in a class and I'm talking about the stage.
    Here is the simplified code in the class:
    package  com.freerangeeggheads.puzzleography {
        import flash.display.MovieClip;
        import flash.events.TouchEvent;
        public class GeoPuzzle extends MovieClip {
            //declare variables
            public function setInitial (abbrev:String, fullName:String, isLocked:Boolean):void {
                //set parameters
                this.addEventListener(TouchEvent.TOUCH_BEGIN, geoTouchBeginHandler);
            public function GeoPuzzle (): void {
            public function geoTouchBeginHandler (e:TouchEvent): void {
                   e.target.addEventListener(TouchEvent.TOUCH_END, geoTouchEndHandler);
                   //some other methods
                   nameDisplay.gotoAndStop(e.target.abbrev);
            public function geoTouchEndHandler (e:TouchEvent): void {
                //some other methods
               nameDisplay.gotoAndStop("USA");
    The lines in bold are my problem. Now this code doesn't actually execute as is so if you see an error in it, yeah, I have no idea what the problem is, but it DID execute before and these lines still gave me trouble so I'm trying to troubleshoot on multiple fronts.
    How can I tell displayName to change it's current frame from within display object class?
    Thanks!

    if displayName is a GeoPuzzle instance, use:
    package  com.freerangeeggheads.puzzleography {
        import flash.display.MovieClip;
        import flash.events.TouchEvent;
        public class GeoPuzzle extends MovieClip {
            //declare variables
            public function setInitial (abbrev:String, fullName:String, isLocked:Boolean):void {
                //set parameters
                this.addEventListener(TouchEvent.TOUCH_BEGIN, geoTouchBeginHandler);
            public function GeoPuzzle (): void {
            public function geoTouchBeginHandler (e:TouchEvent): void {
                   e.target.addEventListener(TouchEvent.TOUCH_END, geoTouchEndHandler);
                   //some other methods
                   this.gotoAndStop(this.abbrev);
            public function geoTouchEndHandler (e:TouchEvent): void {
                //some other methods
               this.gotoAndStop("USA");

  • How do I refer to the stage from a class?

    I have a class that places objects on stage with addChild(obj) it allowes me to position objects using pixels( say obj.x = 10; obj.y= 50; ) just fine but if
    I try this:  obj.x = stage.stageWidth / 2;  I get a message that I Cannot access a property or method of a null object reference

    The stage property is only available to objects that are currently on the display list. Your best bet is probably to pass a stage reference to the class when you instantiate it.

  • Target object on stage from within Class

    Hi,
    I have a custom class which uses some buttons on the stage. Or at least is trying to.
    say have this code in the customClass.as file
    package{
         import flash.events.*;
         import flash.display.MovieClip
         public class customClass{
              public function customCLass (){
                   btn.addEventListener(MouseEvent.MOUSE_OVER , btnOVER);
              private function btnOVER (e:MouseEvent):void{
                  btn.gotoAndStop('over');
    The Lines marked in red throw me this kind of error:
    1120: Access of undefined property btn.

    I am creating the class in a sepparate file.
    when i create an object in this class i pass another object to the class from the timeline. That returns no errors.
    I create objects from the timeline like this:
    var object:customClass = new customClass();

  • Reference to string from another class

    I've searched google and this forum a bit, but can't seem to find an answer. I'd say the thing I'm looking for is really simple and essential, so I must be a moron. But anyways; I want to get the output of the "process" thing in another class. How do I reference to that string fomr outside it's class?
    Thanks.
    public class ReadInput {
         private static void printCommands() {
             System.out.println("blabla");
             System.out.println("blabla");
             System.out.println("blabla");
    public static void process(String in) {
              Do something with the String "in" here. Say, eventually rename it to "output".
    public static void doReadFromStdin() {
         try {
             BufferedReader inStream = new BufferedReader (
                                             new InputStreamReader(System.in)
             String inLine = "";
             String in = inLine;
             while ( !(in.equalsIgnoreCase("quit"))
                     !(in.equalsIgnoreCase("exit")) ) {
                 System.out.print("prompt> ");
                 in = inStream.readLine();
                 process(in);
         } catch (IOException e) {
             System.out.println("IOException: " + e);
    public static void main(String[] args) {
          printCommands();
         doReadFromStdin();
    }

    Maybe this might help
    Igor_Pavlove wrote:
    public static void process(String in) {     
    Do something with the String "in" here. Say, eventually rename it to "output".
    public static String process(String in){
      //Do something, e.g.
      String temp = "ifeeltired";
      return temp;  //Returns the String temp when this method is called.
    public static void main(String[] args) {
         printCommands();
    doReadFromStdin();
    public static void main(String[] args){
      String temp = "thisisaroughexamples";
      String result = this.process(temp); //Returns a string and stores it in result
      CreatePlural.print(result);  //This is possible because the method print() in CreatePlural is static and an instance of CreatePlural is not required.
    }Edited by: Melanie_Green on Feb 2, 2009 6:46 AM
    Edited by: Melanie_Green on Feb 2, 2009 6:47 AM

  • Referencing Stage From External Class

    I have an external class file that extends the MovieClip
    class and is linked to a movieClip on the main stage. I need it to
    be able to access properties of other movieclips on the main stage.
    How could I do this. Here is what my base movieclip class that I
    want to access the stage with looks like. Remember, it is linked to
    a movieclip on the stage, if that matters...
    Obviously there is more code in the class, but I removed it
    for the sake of simplicity.

    that's what I thought too, but it's not working.
    in my document class Main I tried
    mc_bg:MovieClip = new mc_background();
    then i tried passing the mc_bg MovieClip instance to the Background class.
    That gives Error 1180: Call to a Possibly undefined method mc_background.

  • [svn] 4600: Flex SDK - Move style metadata from base class down to component classes

    Revision: 4600
    Author: [email protected]
    Date: 2009-01-20 13:11:33 -0800 (Tue, 20 Jan 2009)
    Log Message:
    Flex SDK - Move style metadata from base class down to component classes
    Previously, all spark and text styles were defined on FxComponent even though not every component supports all of those styles. So I have moved each style to the top-most base class where the style will apply to all descendant classes of that base class.
    This is the set of styles that were added to the various classes:
    baseColor
    color
    focusColor
    symbolColor
    selectionColor
    contentBackgroundColor
    rollOverColor
    alternatingItemColors
    basic text styles
    advanced text styles
    Here are some details about the implementation:
    - baseColor was added to FxComponent because every component and container supports it
    - FxContainer and GroupBase are containers, so their children can potentially support any of the styles. Thus the container classes support all of the styles indirectly.
    - FxDataContainer doesn't support all of the styles because its subclasses (FxButtonBar, FxList) don't support all styles.
    - FxList supports selectionColor, but not inactiveSelectionColor or unfocusedSelectionColor. All other components that support selectionColor, support the other two styles, and thus include styles/metadata/SelectionFormatTextStyles.as
    - GroupBase contains the style declarations that have the full ASDoc. All other declarations use the @copy keyword to reference the asdoc from GroupBase.
    QE Notes: Update tests to remove references to styles that are no longer allowed on various components/FxButton.as
    Doc Notes: Write the ASDoc comments for the style declarations in GroupBase
    Bugs: n/a
    Reviewer: Glenn
    Modified Paths:
    flex/sdk/trunk/frameworks/projects/flex4/src/mx/components/FxButton.as
    flex/sdk/trunk/frameworks/projects/flex4/src/mx/components/FxCheckBox.as
    flex/sdk/trunk/frameworks/projects/flex4/src/mx/components/FxContainer.as
    flex/sdk/trunk/frameworks/projects/flex4/src/mx/components/FxDataContainer.as
    flex/sdk/trunk/frameworks/projects/flex4/src/mx/components/FxList.as
    flex/sdk/trunk/frameworks/projects/flex4/src/mx/components/FxNumericStepper.as
    flex/sdk/trunk/frameworks/projects/flex4/src/mx/components/FxRadioButton.as
    flex/sdk/trunk/frameworks/projects/flex4/src/mx/components/FxScroller.as
    flex/sdk/trunk/frameworks/projects/flex4/src/mx/components/FxSpinner.as
    flex/sdk/trunk/frameworks/projects/flex4/src/mx/components/FxTextArea.as
    flex/sdk/trunk/frameworks/projects/flex4/src/mx/components/baseClasses/FxComponent.as
    flex/sdk/trunk/frameworks/projects/flex4/src/mx/components/baseClasses/FxScrollBar.as
    flex/sdk/trunk/frameworks/projects/flex4/src/mx/components/baseClasses/FxSlider.as
    flex/sdk/trunk/frameworks/projects/flex4/src/mx/components/baseClasses/FxTextBase.as
    flex/sdk/trunk/frameworks/projects/flex4/src/mx/components/baseClasses/GroupBase.as

    Gordon, it looks like its been a while since you made this post.  Not sure how valid it is now...   I am particularly interested in the LigatureLevel.NONE value.  It seems that it is no longer supported.
    How do I turn of ligatures in the font rendering?
    My flex project involves trying to match the font rendering of Apache's Batik rendering of SVG and ligatures have been turned off in that codebase.  Is there any way (even roundabout) to turn ligatures off in flash?
    Thanks,
    Om

  • Calling PopUpManager from a class in a library

    I have a class for logins that I have put in a Flex Library
    Project.
    Part of the login is a popup form(mxml) I have created and is
    in the library.
    The problem I have is this line:
    loginPopUp =
    LoginForm(PopUpManager.createPopUp(this,LoginForm,true));
    The error I get is:
    1067: Implicit coercion of a value of type
    dataManagers:LoginManager to an unrelated type
    flash.display:DisplayObject.
    The parent “this” is no good since its parent
    should be the application that called the logon.
    Can I reference the caller from the LoginManager class I
    created to feed to popupmanager as the parent for the popup?
    The code in the app using the llibray that relates to this
    (to save space) is:
    import dataManagers.LoginManager
    public var lm:LoginManager = new LoginManager();
    lm.initServices();
    //LoginManager.as
    package theLoginManager {
    import flash.events.Event;
    import mx.managers.PopUpManager;
    public class LoginManager {
    import LibraryViews.Login.LoginForm;
    public var loginPopUp:LoginForm;
    public function initServices() : void
    Alert.show("Login start");
    appCFC = new RemoteObject("ColdFusion");
    appCFC.source = "CFC.Users.usersGateway";
    appCFC.addEventListener(FaultEvent.FAULT, server_fault);
    appCFC.init.addEventListener(ResultEvent.RESULT,init_result);
    appCFC.getById.addEventListener(ResultEvent.RESULT,getById_result);
    displayLogin()
    private function displayLogin():void{
    loginPopUp =
    LoginForm(PopUpManager.createPopUp(this,LoginForm,true));//THIS IS
    THE PROBLEM LINE
    loginPopUp.addEventListener("loginSuccessful",
    removeLoginPopup);
    //Removes login form
    private function removeLoginPopup(event:Event):void{
    PopUpManager.removePopUp(loginPopUp);
    }//End Class
    }//End Package
    //LoginForm.mxml
    <?xml version="1.0" encoding="utf-8"?>
    <mx:TitleWindow xmlns:mx="
    http://www.adobe.com/2006/mxml"
    layout="absolute">
    <mx:Form width="100%" height="100%"
    defaultButton="{loginBTN}">
    <mx:FormItem width="100%" label="Username"
    required="true">
    <mx:TextInput id="email"
    width="175" text="mltv"/>
    </mx:FormItem>
    <mx:FormItem width="100%" label="Password"
    required="true">
    <mx:TextInput id="password"
    displayAsPassword="true"
    width="175" text="nuffer"/>
    </mx:FormItem>
    <mx:VBox width="100%" horizontalAlign="center">
    <mx:Button id="loginBTN" label="Login"
    click="authenticateUser();" fillColors="[#80ff00, #80ff00]"/>
    </mx:VBox>
    </mx:Form>
    </mx:TitleWindow>

    I solved it by passing the parent when I called it from the
    parent project:
    lm.initServices(this);
    and then created a var in the .as file:
    private var theCallingParent:DisplayObject;
    theCallingParent = theParent;
    Then used that variable when I called the popup:
    loginPopUp =
    LoginForm(PopUpManager.createPopUp(theCallingParent,LoginForm,true));
    Sorry to clog up the board.

  • Can't get stage from a constructor method. Why?

    Hi,
    I'm making a kind of image showcase, what has a fluid width and height, depending on browser window dimensions. Everything is okay, I have other kind of issue: in constructor function in this gallery class I can't use stage property, I have to get it from main class.
    Why Flash treats me this way and how I can avoid this currentStage variable?
    Main code:
    package dev {
         import flash.display.Sprite;
         import flash.display.StageScaleMode;
         import flash.display.StageAlign;
         import flash.display.MovieClip;
         import flash.events.Event;
         import UI.BackgroundImageRotator;
         public class Application extends Sprite {
              public function Application():void {
                   stage.scaleMode = StageScaleMode.NO_SCALE;
                   stage.align = StageAlign.TOP_LEFT;
                   trace("Start.");
                   var BIR = new BackgroundImageRotator(stage);
                   stage.addChild(BIR);
    BackgroundImageRotator class:
    package UI {
         import flash.display.MovieClip;
         import flash.events.Event;
         import flash.display.Stage;
         public class BackgroundImageRotator extends MovieClip {
              protected var currentStage:Stage;
              public function BackgroundImageRotator(currentStage:Stage):void {
                   this.x = 0;
                   this.y = 0;
                   this.currentStage = currentStage;
                   currentStage.addEventListener(Event.RESIZE, onStageResize);
              protected function onStageResize(evt:Event):void {
                   trace(stage.stageWidth + ' ' + stage.stageHeight);

    if you have a display object that will be added to the display list, you need to wait until it is added before you can reference its stage property.  ie, use the Event.ADDED_TO_STAGE event.
    otherwise, you must pass a stage reference to your class.

  • How can I assign image file name from Main() class

    I am trying to create library class which will be accessed and used by different applications (with different image files to be assigned). So, what image file to call should be determined by and in the Main class.
    Here is the Main class
    import org.me.lib.MyJNIWindowClass;
    public class Main {
    public Main() {
    public static void main(String[] args) {
    MyJNIWindowClass mw = new MyJNIWindowClass();
    mw.s = "clock.gif";
    And here is the library class
    package org.me.lib;
    public class MyJNIWindowClass {
    public String s;
    ImageIcon image = new ImageIcon("C:/Documents and Settings/Administrator/Desktop/" + s);
    public MyJNIWindowClass() {
    JLabel jl = new JLabel(image);
    JFrame jf = new JFrame();
    jf.add(jl);
    jf.setVisible(true);
    jf.pack();
    I do understand that when I am making reference from main() method to MyJNIWindowClass() s first initialized to null and that is why clock could not be seen but how can I assign image file name from Main() class for library class without creating reference to Main() from MyJNIWindowClass()? As I said, I want this library class being accessed from different applications (means different Main() classes).
    Thank you.

    Your problem is one of timing. Consider this simple example.
    public class Example {
        public String s;
        private String message = "Hello, " + s;
        public String toString() {
            return message;
        public static void main(String[] args) {
            Example ex = new Example();
            ex.s = "world";
            System.out.println(ex.toString());
    }When this code is executed, the following happens in order:
    1. new Example() is executed, causing an object to constructed. In particular:
    2. field s is given value null (since no value is explicitly assigned.
    3. field message is given value "Hello, null"
    4. Back in method main, field s is now given value "world", but that
    doesn't change message.
    5. Finally, "Hello, null" is output.
    The following fixes the above example:
    public class Example {
        private String message;
        public Example(String name) {
            message = "Hello, " + name;
        public String toString() {
            return message;
        public static void main(String[] args) {
            Example ex = new Example("world");
            System.out.println(ex.toString());
    }

  • Calling a method from another class while in a seperate class

    Hello
    I am currently TRYING to proramme a simple alarm clock program, The way it has had to be set out is that there are two classes one is called ClockDisplay which is just the clock and the one i have had to create is called AlarmDisplay
    I am trying to write code so that when the String alarmdisplayString(this is located in the alarm class which i am typing this code) is the same as String displayString the system will print out something like "Beep wake up" So far i have this code but i cannot figue out what to put to reference the method from the ClockDisplay class while codingi n the AlarmDisplay class
    if(alarmdisplayString = DONT KNOW WHAT TO PUT HERE) {
    system.out.println ("DING WAKE UP");
    Any help would be great!
    Thanks

    That makes sense i have put in this code
    private void Alarmtone()
    ClockDisplay displayString = new ClockDisplay();
    if (alarmdisplayString == ClockDisplay.displayString){
    system.out.println ("DING WAKE UP");
    displayString is the method in the ClockDisplay Class
    alarmdisplayString is the method in the AlarmDisplay class
    I get the error message "non-static variable displayString cannot be referenced from a static context
    Thanks for the help so far :D

  • Calling method from another class problem

    hi,
    i am having problem with my code. When i call the method from the other class, it does not function correctly?
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class Dice extends JComponent
        private static final int SPOT_DIAM = 9; 
        private int faceValue;   
        public Dice()
            setPreferredSize(new Dimension(60,60));
            roll(); 
        public int roll()
            int val = (int)(6*Math.random() + 1);  
            setValue(val);
            return val;
        public int getValue()
            return faceValue;
        public void setValue(int spots)
            faceValue = spots;
            repaint();   
        @Override public void paintComponent(Graphics g) {
            int w = getWidth(); 
            int h = getHeight();
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setColor(Color.WHITE);
            g2.fillRect(0, 0, w, h);
            g2.setColor(Color.BLACK);
            g2.drawRect(0, 0, w-1, h-1); 
            switch (faceValue)
                case 1:
                    drawSpot(g2, w/2, h/2);
                    break;
                case 3:
                    drawSpot(g2, w/2, h/2);
                case 2:
                    drawSpot(g2, w/4, h/4);
                    drawSpot(g2, 3*w/4, 3*h/4);
                    break;
                case 5:
                    drawSpot(g2, w/2, h/2);
                case 4:
                    drawSpot(g2, w/4, h/4);
                    drawSpot(g2, 3*w/4, 3*h/4);
                    drawSpot(g2, 3*w/4, h/4);
                    drawSpot(g2, w/4, 3*h/4);
                    break;
                case 6:
                    drawSpot(g2, w/4, h/4);
                    drawSpot(g2, 3*w/4, 3*h/4);
                    drawSpot(g2, 3*w/4, h/4);
                    drawSpot(g2, w/4, 3*h/4);
                    drawSpot(g2, w/4, h/2);
                    drawSpot(g2, 3*w/4, h/2);
                    break;
        private void drawSpot(Graphics2D g2, int x, int y)
            g2.fillOval(x-SPOT_DIAM/2, y-SPOT_DIAM/2, SPOT_DIAM, SPOT_DIAM);
    }in another class A (the main class where i run everything) i created a new instance of dice and added it onto a JPanel.Also a JButton is created called roll, which i added a actionListener.........rollButton.addActionListener(B); (B is instance of class B)
    In Class B in implements actionlistener and when the roll button is clicked it should call "roll()" from Dice class
    Dice d = new Dice();
    d.roll();
    it works but it does not repaint the graphics for the dice? the roll method will get a random number but then it will call the method to repaint()???
    Edited by: AceOfSpades on Mar 5, 2008 2:41 PM
    Edited by: AceOfSpades on Mar 5, 2008 2:42 PM

    One way:
    class Flintstone
        private String name;
        public Flintstone(String name)
            this.name = name;
        public String toString()
            return name;
        public static void useFlintstoneWithReference(Flintstone fu2)
            System.out.println(fu2);
        public static void useFlintstoneWithOutReference()
            Flintstone barney = new Flintstone("Barney");
            System.out.println(barney);
        public static void main(String[] args)
            Flintstone fred = new Flintstone("Fred");
            useFlintstoneWithReference(fred); // fred's the reference I"m passing to the method
            useFlintstoneWithOutReference();
    {code}
    can also be done with action listener
    {code}    private class MyActionListener implements ActionListener
            private Flintstone flintstone;
            public MyActionListener(Flintstone flintstone)
                this.flintstone = flintstone;
            public void actionPerformed(ActionEvent arg0)
                //do whatever using flinstone
                System.out.println(flintstone);
        }{code}
    Edited by: Encephalopathic on Mar 5, 2008 3:06 PM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Calling a non-static method from another Class

    Hello forum experts:
    Please excuse me for my poor Java vocabulary. I am a newbie and requesting for help. So please bear with me! I am listing below the program flow to enable the experts understand the problem and guide me towards a solution.
    1. ClassA instantiates ClassB to create an object instance, say ObjB1 that
        populates a JTable.
    2. User selects a row in the table and then clicks a button on the icon toolbar
        which is part of UIMenu class.
    3. This user action is to invoke a method UpdateDatabase() of object ObjB1. Now I want to call this method from UIMenu class.
    (a). I could create a new instance ObjB2 of ClassB and call UpdateDatabase(),
                                      == OR ==
    (b). I could declare UpdateDatabase() as static and call this method without
         creating a new instance of ClassB.With option (a), I will be looking at two different object instances.The UpdateDatabase() method manipulates
    object specific data.
    With option (b), if I declare the method as static, the variables used in the method would also have to be static.
    The variables, in which case, would not be object specific.
    Is there a way or technique in Java that will allow me to reference the UpdateDatabase() method of the existing
    object ObjB1 without requiring me to use static variables? In other words, call non-static methods in a static
    way?
    Any ideas or thoughts will be of tremendous help. Thanks in advance.

    Hello Forum:
    Danny_From_Tower, Encephalatic: Thank you both for your responses.
    Here is what I have done so far. I have a button called "btnAccept" created in the class MyMenu.
    and declared as public.
    public class MyMenu {
        public JButton btnAccept;
         //Constructor
         public MyMenu()     {
              btnAccept = new JButton("Accept");
    }     I instantiate an object for MyMenu class in the main application class MyApp.
    public class MyApp {
         private     MyMenu menu;
         //Constructor     
         public MyApp(){
              menu = new MyMenu();     
         public void openOrder(){
               MyGUI MyIntFrame = new MyGUI(menu.btnAccept);          
    }I pass this button all the way down to the class detail02. Now I want to set up a listener for this
    button in the class detail02. I am not able to do this.
    public class MyGUI {
         private JButton acceptButton;
         private detail02 dtl1 = new detail02(acceptButton);
         //Constructor
         public AppGUI(JButton iButton){
         acceptButton = iButton;
    public class detail02{
        private JButton acceptButton;
        //Constructor
        public detail02(JButton iButton){
          acceptButton = iButton;
          acceptButton.addActionListener(new acceptListener());               
       //method
        private void acceptListener_actionPerformed(ActionEvent e){
           System.out.println("Menu item [" + e.getActionCommand(  ) + "] was pressed.");
        class acceptListener implements ActionListener {       
            public void actionPerformed(ActionEvent e) {
                   acceptListener_actionPerformed(e);
    }  I am not able to get the button Listener to work. I get NullPointerException at this line
              acceptButton.addActionListener(new acceptListener());in the class detail02.
    Is this the right way? Or is there a better way of accomplishing my objective?
    Please help. Your inputs are precious! Thank you very much for your time!

Maybe you are looking for