Referencing main class from created instances

The quick setup:
My Main class creates a JFrame and adds a few custom JPanels. One of the JPanels has a mouse listener and responses to the mouse clicks, and it works great.
I'd like to know if there's a way to have that JPanel invoke public, non-static methods from the Main class (the class which created it) without passing a reference for the instance of the Main class to the JPanel when it's (the JPanel) is created. Or is that the way you're supposed to do it?
A (sort of) similar question: can a component invoke methods of it's parent container? If so, how?
Thanks so much,
Matt

Hi Rhesus21,
A (sort of) similar question: can a component invoke methods of it's parent container? If so, how?Yes, simply this way :
public class MainFrame extends JFrame {
    private MyPanel panel;
    panel = new MyPanel(this);
public class MyPanel extends JPanel {
    private MainFrame frame;
    public MyPanel(MainFrame frame) {
        this.frame = frame;
}

Similar Messages

  • Accessing object of the main class from the thread

    Hi, I'm having problem accessing object of the main class from the thread. I have only one Thread and I'm calling log.append() from the Thread. Object log is defined and inicialized in the main class like this:
    public Text log;  // Text is SWT component
    log = new Text(...);Here is a Thread code:
    ...while((line = br.readLine())!=null) {
         try {
              log.append(line + "\r\n");
         } catch (SWTException swte) {
              ErrorMsg("SWT error: "+swte.getMessage());
    }Error is: org.eclipse.swt.SWTException: Invalid thread access
    When I replace log.append(...) with System.out.println(..) it works just fine, so my question is do the log.append(..) the right way.

    This is NOT a Java problem but a SWT specific issue.
    It is listed on the SWT FAQ page http://www.eclipse.org/swt/faq.php#uithread
    For more help with this you need to ask your question on a SWT specific forum, there is not a thing in these forums. This advice isn't just about SWT by the way but for all specific API exceptions/problems. You should take those questions to the forum or mailing list for that API. This forum is for general problems and exceptions arising from using the "core" Java libraries.

  • Referencing host class from a thread?

    Hello, I need some help with the logic of this. How would I reference the host class (the class that created the thread) from the thread. I want to send a string from a thread (where it is grabbed from the command line) to the class which made the thread.. Thanks!

    Just like when any object of one class needs to access another object. Somewhere you'll have to pass the "host class" (actually "host object reference" is more close) to the thing that implements Runnable or extends Thread (however you designed it), so that the object can hold and use a reference to it.

  • Referencing utility classes from a war file

    How do you reference a utility class from a war file? I tried adding the class to the deployment plan descriptor, however I still get a ClassNotFoundException.
    Thanks,
    Will

    To use the utility classes from a war you have to place them under the web-inf/classes directory.
    webApplication(WAR directory)--->WEB-INF--> classes (put your utility classes in this directory)

  • Referencing a class that created another class

    Is there a certain way reference the class that created "you" - examples:
    public class SomeClass
      public SomeClass()
        // blah blah
        SomeOtherClass foo = new SomeOtherClass();
    public class SomeOtherClass
      public SomeOtherClass()
        // blah
      public void SomeMethod()
        // access SomeClass here
        TheClassThatCreatedMe.method();
    }Any ideas?

    one way is u can modify ur code this way
    public class SomeClass{  public SomeClass()  {    // blah blah    SomeOtherClass foo = new SomeOtherClass(String creator);  }}
    //where string creator u pass the same clasas name i.e someclass
    public class SomeOtherClass{  public SomeOtherClass()  {
    System.out.println("created class name is "+creator );
    // blah
    } public void SomeMethod() {    // access SomeClass here    TheClassThatCreatedMe.method();  }}

  • Running one main class from another

    Hey, i developed two main class. Each class produce it's one JFrame. One Frame suppose to at one point run the other frame when a start button is press. How should I go about doing it?

    You can just call the other class's main method.
    However, that's kind of messy. If you have any functionality in your main method other than just bootstrapping your program, it's probably better to refactor it out into a different method. Then your other class can invoke that new method.

  • Pass parameters to a function in main class from loaded SWF?

    I've got a main.as that loads SWF to the stage.
    the loaded SWF seppoused to pass a link to the main.as and trigger a javascript function to popUp that photo from that link.
    I know there are two ways:
    ((root as MovieClip).parent.parent as Object).somefunction(parameters);
    and to dispatch an event.
    inorder to pass parameters throug the event i need to extend it with another class.
    isnt the (root as... )  more efficient if all i need is to pass a link?

    when a photo from the gallery is selected a javascript popUp shows it enlarged with additioan editing options (kinda like in facebook).
    in that popUp ther is also a next button so its kinda bidirectional. (the next calling the loaded SWF throug main to get the next link in the photo array)
    the photo is a grandchild of a grandchild of the stage and the loaded swf is a grandchild so using:
    ((root as MovieClip).root as MovieClip).ExternalInterface.call("ShowPic", link);
    is discusting ><

  • Referencing a Class from a Variable

     

    sorry I also forgot to mention that I'm putting in values for _gameModel.scroll_Vx, and Vy from another class, the scroll class. When I try to reference the var from other classes it works but not the FirstEnemy Class.

  • Trying to access methods from a .class file by creating instance of class

    Hey all,
    I'm hoping you can help. I've been given a file "Input.class" with methods such as readInt(), readString(), etc. I have tried creating instances of this class to make use of it, but I receive the error "cannot find symbol : class Input".
    If you could help at all, I would greatly appreciate it.
    Here's my code. The first is the base program, the second is the driver.
    import java.util.*;
    public class CarObject
         private String makeType = "";
         private String modelType = "";
         private int yearOfRelease = 0;
         private double numOfMiles = 0.0;
         public void setFilmTitle(String make)
              makeType = make;
         public void setMediaType(String model)
              modelType = model;
         public void setYearOfRelease(int year)
              yearOfRelease = year;
         public void setNumOfMiles(double miles)
              numOfMiles = miles;
         public String getMakeType()
              return makeType;
         public String getModelType()
              return modelType;
         public int getYearOfRelease()
              return yearOfRelease;
         public double getNumOfMiles()
              return numOfMiles;
    The program is used by a rental car company and the object takes on desired attributes.
    import java.util.*;
    public class TestCarObject
         static Scanner keyboard = new Scanner(System.in);
         public static void main(String[] args)
              System.out.println("Please answer the following questions regarding your rental car order.");
              Input carinput = new Input();
              String makeType = carinput.readString("Enter your desired make of car: ");          
              String modelType = carinput.readString("Enter your desired model of car: ");
              int yearOfRelease = carinput.readInt("Enter the oldest acceptable year of release to rent: ");
              double numOfMiles = carinput.readDouble("Enter the highest acceptable number of miles: ");
              System.out.println("Make: " + makeType);
              System.out.println("Model: " + makeType);
              System.out.println("Year: " + makeType);
              System.out.println("Mileage: " + makeType);
    }

    No, I don't know the package name....Is there a way
    to import the Input.class by itself without importing
    the entire packge?
    I tried extending the driver program too...It didn't
    work either...
    Message was edited by:
    BoxMan56How do you know you have a class called Input.class ?
    You got a jar file which contains it ? or just a simple .class file ?
    You have to set the classpath in either case.
    But for the former, you should also need to explicitly telling which package containing the class file you looking for (i.e. Input.class)
    e.g. java.util.Vector which is a class called Vector inside java.util package.
    You don't have to import the whole package, but you should tell which package this class belongs to.

  • Coldfusion create instance of class from data element when cosuming a webservice

    I am calling the following wsdl via cfobject https://services-staging.labcorpsolutions.com/webservice/services/LabcorpOTS/wsdl/LabcorpO TS.wsdl
    I am attempting to call the following method registerDonor(java.lang.String, java.lang.String, com.labcorp.ots.ws.data.CreateRegistrationRequest) which references the CreateRegistrationRequest data element.
    I haven't been successful in creating an instance of the CreateRegistrationRequest class and setting values of its members, as well as the Phone class which is also a data element.
    Any assistance would be greatly appreciated in creating instances of methods located in the targetNamespace="http://data.ws.ots.labcorp.com" of the wsdl.
    Thanks

    Thanks for the explanation and example. At first, I didn't understand what you were getting at, but after reading "Using Top-Level Containers" and "How to Use Root Panes" java tutorials it made much more sense. Unfortunately, the books I've read up to this point, did not cover those topics at all. The books simply stated that the first step in creating a Swing gui was to extend the JFrame, or JApplet, or etc.
    Unfortunately, my original problem persists. I continue to get compile-time errors such as:
    TestUserInterface.java:5: cannot find symbol
    symbol: class UserInterface
    location: class projects.web.TestUserInterface
                          UserInterface ui = new UserInterface(); Anyone know why?
    Both the classes are in the same named packaged. Below is my code:
    package projects.web;
    import java.awt.*;
    import javax.swing.*;
    public class UserInterface extends JFrame{
         JPanel menuPanel = new JPanel();
         JPanel contentPanel = new JPanel();
         JPanel selectionPanel = new JPanel();
         JButton save = new JButton("Save");
         JButton addFiles = new JButton("Add");
         public UserInterface(){
         super("File Upload");
         setSize(500, 500);
         menuPanel.add(addFiles);
         selectionPanel.add(save);
         setLayout(new BorderLayout());
         add(menuPanel, BorderLayout.NORTH);
         add(contentPanel, BorderLayout.CENTER);
         add(selectionPanel, BorderLayout.SOUTH);
         } // end constructor
    } // end UserInterface class
    package projects.web;
    public class TestUserInterface{
         public static void main(String[] args){
              UserInterface ui = new UserInterface();
    } // end TestUserInterface class

  • How to call a method from a class without creating an instance fromthisclas

    I want to create a class with methods but I want to call methods from this class without creating an instance from this class. Is this possible?
    Is there in Java something like class methods and object methods????

    keyword 'static' my friend.
    public class foo {
    public static void bar {
    System.out.println ("hello");
    foo.bar()

  • Instance of a Main Class

    Hi guys,
    I need to create an instance of the main class in my project.
    This main has the standard main method : public static void main (String args[])
    ,which requires a character by command line.
    How to create an instance of this class from another class in the same project passing the required parameter ??
    Note : I'm using this to test the class , with Eclipse and Junit
    Thanks a lot

    Same way you create any other class. Except "main" is a static method, so you don't need to create the class. Just call the following:
    Main.main(new String[] {"FirstArg", "SecondArg", "ThirdArg"});Where Main is the class with your "main" method. You can build up the String array separately, and then pass it as the argument to "main" (as you would for any other method that takes a String array).

  • Creating a Button Class from MC

    I have a few simple questions for those who know about
    classes. I have been reading the tutorials on creating classes and
    specifically extending the MC class. I am pretty sure that an
    extended MC_Class might help me get what I need from my project.
    I essentially have a bunch of buttons, hundreds to be exact -
    and the exact number needs to be dynamic. Each one is currently a
    static MC with a bunch of variables assigned to each one via global
    variables. Its iis pulling in data taht assign the button values
    from XML files and - these XML files may change.
    Q1. If I extend the MC class so I can add attributes to MC's
    instance (Avoiding global variables) - will it mess with the rest
    of the movie clips in my scene? I mean if all I want to do is ad a
    a few dynamic string variables - it really shouldnt effect any of
    the other clips would it? MC.JumpURL = "newurl.com", MC.Thumnail
    ="/here/image.jpg" (This would help alot)
    Q2. What if I wanted to define actions of the new MC in the
    class? If the MC is an extension of the MC class. Would all of my
    MC's automatically take on the actions of the custom MC Class? For
    instance - I want the movieclip to animate onscreen and have
    rollover effects. I could do this easy if it were static - but I
    need this to become dynamic. Also - there are now unknown
    quantities to deal with
    Q3. How exactly would I call and assign the MC its atributes
    at the same time? And how do I specify this MC to use the functions
    defined in the class and not the other MC's I created elsewhere in
    the File.
    Example. Currently I have a grid of MCs' created when the
    User clicks a menu item (Another type of MC).
    Each new MC animates onstage - it calls a
    loadMovie(_root.thumb[0], this.Flipper) to assign and embedded MC
    an image defined in the XML that was loaded and assigned because I
    placed the instance on stage and wrote a MC script on each MC.
    Confused - check out what I am creating at
    www.vincesidwell.com/Fischer
    Click Fabrication or TurboSystems menus. Both menues will
    load a new set of Thumbnails at the bottom. They are loaded via an
    XML loaded by the menu and a function assigns the jpgs for the main
    gallery, Rollover image, and eventually a URL for a downloadable
    High Res Image.
    The client recently added more than 9 images per menu item. I
    will need to create a scrollable thumbnail gallery with dynamic
    quantities
    I can manually create the MC Scroller item for static number
    of buttons. But scripting an unknown for each ones links and images
    is insane. So I am looking at Classes. Assign a custom class for
    the flipping buttons and I should be able to assign tthem as the
    XML loads, and have it automatic. (pray please please please)
    Anyhelp?
    Thanks
    Vince Sidwell

    Hi there!
    I'll try and give some answers to your questions below...
    "vin-E" <[email protected]> wrote in message
    news:[email protected]...
    >I have a few simple questions for those who know about
    classes. I have
    >been
    > reading the tutorials on creating classes and
    specifically extending the
    > MC
    > class. I am pretty sure that an extended MC_Class might
    help me get what
    > I
    > need from my project.
    >
    > I essentially have a bunch of buttons, hundreds to be
    exact - and the
    > exact
    > number needs to be dynamic. Each one is currently a
    static MC with a
    > bunch of
    > variables assigned to each one via global variables. Its
    iis pulling
    > in
    > data taht assign the button values from XML files and -
    these XML files
    > may
    > change.
    >
    > Q1. If I extend the MC class so I can add attributes to
    MC's instance
    > (Avoiding global variables) - will it mess with the rest
    of the movie
    > clips in
    > my scene? I mean if all I want to do is ad a a few
    dynamic string
    > variables -
    > it really shouldnt effect any of the other clips would
    it? MC.JumpURL =
    > "newurl.com", MC.Thumnail ="/here/image.jpg" (This would
    help alot)
    You do not have to create a new MC class to assign local
    values or functions
    to it. A pseudo code example:
    Loop through total buttons you want to make (which can be
    number of entries
    in an XML file)
    Create a new movieclip and load the button graphic into
    this, give it a
    name like
    MyButtonX, where X is an increasing number based on which
    button this
    is. (Instead of creating
    and empty movielcip, you could also attach a movie (or
    button) from
    library.
    Assign the values and create the functions for this button
    that you
    would like (probably based
    on information in the XML file):
    MyButtonX.someVariable = node.attribues.someData;
    createOnRelease(MyButtonX, someOtherParamters)
    (where you have defined the function createOnRelease to do
    something
    like
    function createOnRelease(MC, someOtherParameteres) {
    MC.onRelease = function() {
    do what you want to do based on someOtherParameteres
    Position and resize MyButtonX
    In your example you have a 3x3 grid, which might extend to
    3xTOTAL,
    so you'd have to use some
    mathematical formula based on the value X, something like
    MyButtonX._x =
    (((X-1)%3)*(buttonWidths+hSpaceBetweenButtons)
    MyButtonY._y = Math.floor((X-1)/3)*(buttonHeights
    +vSpaceBetweenButtons
    end of loop.
    >
    > Q2. What if I wanted to define actions of the new MC in
    the class? If
    > the MC
    > is an extension of the MC class. Would all of my MC's
    automatically take
    > on
    > the actions of the custom MC Class? For instance - I
    want the movieclip
    > to
    > animate onscreen and have rollover effects. I could do
    this easy if it
    > were
    > static - but I need this to become dynamic. Also - there
    are now unknown
    > quantities to deal with
    If you actually create a new class, than all instances of
    that class will
    have the methods you define for it (just like all instances
    of a movieclip
    has those methods. At least, have them available. That
    doesn't mean they are
    always in use ... like for example the onRollOver. But again,
    you don't need
    to create a class to give all your dynamically created
    buttons a rollover
    effect. (Check code above).
    > Q3. How exactly would I call and assign the MC its
    atributes at the same
    > time? And how do I specify this MC to use the functions
    defined in the
    > class
    > and not the other MC's I created elsewhere in the File.
    You use the instance name of the MC to access that MC and its
    attributes/methods. For example button number 10 might look
    like this:
    trace(MyButton10._x);
    trace(MyButton10.someVariableYouHaveDefined);
    MyButton10.callSomeFunctionYouHaveDefined();
    For a movieclip to access a variable that has been defined
    for that instance
    of the movieclip, use "this" to point to that particular
    instance. So if we
    defined the function "callSomeFunctionYouHaveDefined" for
    button number 10
    and want to access "someVariableYouHaveDefined" for this
    particular
    instance, then
    MyButton10.callSomeFunctionYouHaveDefined = function() {
    trace(this.someVariableYouHaveDefined);
    > Example. Currently I have a grid of MCs' created when
    the User clicks a
    > menu
    > item (Another type of MC).
    > Each new MC animates onstage - it calls a
    loadMovie(_root.thumb[0],
    > this.Flipper) to assign and embedded MC an image defined
    in the XML that
    > was
    > loaded and assigned because I placed the instance on
    stage and wrote a MC
    > script on each MC.
    >
    > Confused - check out what I am creating at
    www.vincesidwell.com/Fischer
    >
    > Click Fabrication or TurboSystems menus. Both menues
    will load a new set
    > of
    > Thumbnails at the bottom. They are loaded via an XML
    loaded by the menu
    > and a
    > function assigns the jpgs for the main gallery, Rollover
    image, and
    > eventually
    > a URL for a downloadable High Res Image.
    >
    > The client recently added more than 9 images per menu
    item. I will need
    > to
    > create a scrollable thumbnail gallery with dynamic
    quantities
    >
    > I can manually create the MC Scroller item for static
    number of buttons.
    > But
    > scripting an unknown for each ones links and images is
    insane. So I am
    > looking
    > at Classes. Assign a custom class for the flipping
    buttons and I should
    > be
    > able to assign tthem as the XML loads, and have it
    automatic. (pray please
    > please please)
    Again, no need for a class for this. If you load the buttons
    into seperate
    MCs, and make sure to have all these MCs created inside a
    common parent MC
    for these buttons (which then _only_ contains these buttons).
    You can move
    this parent MC up and down on the stage based on the
    scrollbar. And you can
    read height off this MC to create your scrollbar.
    You might want to check out the following tutorials at
    http://www.gotoandlearn.com/:
    XML Video Playlist
    Creating Animated Buttons
    Introduction to OOP
    Now, I've said many times you don't need to make your own
    class to do what
    you want. That does not mean you can't make your own class. I
    just think
    that the main problem you are facing is the dynamic part,
    which you will be
    facing if you make your own class or not.
    /Jensen/
    >
    > Anyhelp?
    >
    > Thanks
    > Vince Sidwell
    >
    >
    >

  • 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());
    }

  • Using Class and Constructor to create instances on the fly

    hi,
    i want to be able to create instances of classes as specified by the user of my application. i hold the class names as String objects in a LinkedList, check to see if the named class exists and then try and create an instance of it as follows.
    the problem im having is that the classes i want to create are held in a directory lower down the directory hierarchy than where the i called this code from.
    ie. the classes are held in "eccs/model/behaviours" but the VM looks for them in the eccs directory.
    i cannot move the desired classes to this folder for other reasons and if i try to give the Path name to Class.forName() it will not find them. instead i think it looks for a class called "eccs/model/behaviours/x" in the eccs dir and not navigate to the eccs/model/behaviours dir for the class x.
    any ideas please? heres my code for ye to look at in case im not making any sense:)
    //iterator is the Iterator of the LinkedList that holds all the names of the
    //classes we want to create.
    //while there is another element in the list.
    while(iterator.hasNext())
    //get the name of the class to create from the list.
    String className = (String) iterator.next();
    //check to see if the file exists.
    if(!doesFileExist(className))
    System.out.println("File cannot be found!");
    //breake the loop and move onto the next element in the list.
    continue;
    //create an empty class.
    Class dynamicClass = Class.forName(className);
    //get the default constructor of the class.
    Constructor constructor = dynamicClass.getConstructor(new Class[] {});
    //create an instance of the desired class.
    Behaviour beh = (Behaviour) constructor.newInstance(new Object[] {});
    private boolean doesFileExist(String fileName)
    //append .class to the file name.
    fileName += ".class";
    //get the file.
    File file = new File(fileName);
    //check if it exists.
    if(file.exists())
    return true;
    else
    return false;
    }

    ok ive changed it now to "eccs.model.behaviours" and it seems to work:) many thanks!!!
    by the following you mean that instead of using the method "doesFileExist(fileName)" i just catch the exception and throw it to something like the System.out.println() ?
    Why don't you simply try to call Class.forName() and catch the exception if it doesn't exist? Because as soon as you package up your class files in a jar file (which you should) your approach won't work at all.i dont think il be creating a JAR file as i want the user to be able to create his/her own classes and add them to the directory to be used in the application. is this the correct way to do this??
    again many thanks for ye're help:)

Maybe you are looking for

  • Pointers on ABAP documentations (Database/Respositories/Structures/Tables/

    Hi ABAP Gurus/Experts, I am basically a SAP Functional consultant, but recently taken a new assignment on SAP Net Weaver MDM, where in i require lot of ABAP knowledge mainly in Database area, like Structure, Tables, Data Objects etc, I am looking for

  • Unable to export real data

    dear experts, I have tried to find discussions on this already but after wadding through a few pages, I thought I could be helped faster if I threaded this topic. I have been able to successfully log into an oracle db and was looking to export about

  • Updating the description field on the CRM Service Order

    HI Experts, I want to update the description fied with the service order number on the service order. What is the procedure to update the screen field on the crm service order, is it by order_maintain. Thanks in Advance for your help, Praveen

  • Machine Authentication with PEAP on Wireless with ISE1.2

    Hi All, We are facing issues while doing machine authentication in ISE1.2 with wireless PEAP authentication. Without machine authentication normal PEAP works very fine but as soon as we enable machine authentication and create policy for machine auth

  • Compaq nc6000 not charging the battery

    Hello, I'm having a problem with a Compaq nc6000 I'm trying to fix up for a freind.  It doesn't appear to be charging the battery.  It will run off the battery and the external power just fine, but the charging indicator does not come on and the powe