Invoke a method in one class from a different class

I am working on a much larger project, but to keep this simple, I wrote out a little test that would convey the over all theory of the program.
What I am doing is starting out with a 2 JFrames and a Class. When the program is launched, the first JFrame opens. In this JFrame is a label and a button. When the button is clicked, the second JFrame opens. This JFrame has a textField and a button. The user puts the text in the textField and presses the button. When the button is pushed, I want the text that was just put in the textField, to be displayed in the first JFrame's label. I am trying to invoke a method in the first JFrame from the second, but nothing happens. I have also tried making the Class extend from JFrame1 and invoke it from there, but no luck. So, how do I invoke a method in a class from a different class?
JFrame1 (I omitted the layout part. I made this in Netbeans so its pretty long)
public class NewJFrame1 extends javax.swing.JFrame {
     private NewClass1 nC = new NewClass1();
     /** Creates new form NewJFrame1 */
     public NewJFrame1() {
          initComponents();
          jLabel1.setText("Chuck");
     public void setLabels()
          jLabel1.setText(nC.getName());
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                                  
     NewJFrame2 j2 = new NewJFrame2();
     j2.setVisible(true);The class
public class NewClass1 {
     public static String name;
     public NewClass1()
     public NewClass1(String n)
          name = n;
     public String getName()
          return name;
     public void setName(String n)
          name = n;
}The second jFrame
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                                  
     NewClass1 nC = new NewClass1();
     NewJFrame1 nF = new NewJFrame1();     
     nC.setName(jTextField1.getText());
     nF.setLabels();
     System.out.println(nC.getName());At this point I am begging for help. I have been trying for days to figure this out, and I just feel like I am not getting anywhere.
Thanks

So, how do I invoke a method in a class from a different class?Demo:
public class Main {
    public static void main(String [] args) {
     Test1 t1 = new Test1();
     Test2 t2 = new Test2();
     int i = t1.method1();
     String s = t2.method2(i);
     System.out.println(s);
class Test1 {
    public int method1() {
     return 10;
class Test2 {
    public String method2(int i) {
     if (i == 10)
         return "ten";
     else
         return "nothing";
}Output is "ten".
Edited by: newark on May 28, 2008 10:55 AM

Similar Messages

  • Calling a method of one class from another withing the same package

    hi,
    i've some problem in calling a method of one class from another class within the same package.
    for eg. if in Package mypack. i'm having 2 files, f1 and f2. i would like to call a method of f2 from f1(f1 is a servlet) . i donno exactly how to instantiate the object for f2. can anybody please help me in this regard.
    Thank u in advance.
    Regards,
    Fazli

    This is what my exact problem.
    i've created a bean (DataBean) to access the database. i'm having a servlet program (ShopBook). now to check some details over there in the database from the servlet i'm in need to use a method in the DataBean.
    both ShopBook.java and DataBean.java lies in the package shoppack.
    in ShopBook i tried to instantiate the object to DataBean as
    DataBean db = new DataBean();
    it shows the compiler error, unable to resolve symbol DataBean.
    note:
    first i compiled DataBean.java, it got compiled perfectly and the class file resides inside the shoppack.
    when i'm trying to compile the ShopBook its telling this error.
    hope i'm clear in explaining my problem. can u please help me?
    thank u in advance.
    regards,
    Fazli

  • Can I Call method on one JVM from another through a dll?

    Let me explain.
    I have this java jar file that I can only have one instance of running at any given time. I'm using a shared data segment in a dll to store a bool indicating whether the program is already running or not. If it's already running, I have to not run the second instance and give focus to the current running instance.
    The jar file calls a native method "canInstantiate()" on a dll to see if there's already an app running. If there isn't, the env and obj are stored in the shared data segment of the dll and we return true. If there is already an instance of the program running, I want canInstantiate call a function on the current instance of the jar (like a callback) to tell it to request focus. It's not working. Can someone tell me if my code is right?
    The .h file
    #include "stdafx.h"
    #include <jni.h>
    #include "CardServer.h"
    #pragma data_seg("SHARED") // Begin the shared data segment.
    static volatile bool instanceExists = false;
    static JavaVM *theJavaVM = NULL;
    static JNIEnv* theJavaEnv= NULL;
    static jobject instanceObject = NULL;
    static jmethodID mid = NULL;
    static jclass cls = NULL;
    #pragma data_seg()
    #pragma comment(linker, "/section:SHARED,RWS")
    jdouble canInstantiate(JNIEnv *env, jobject obj);
    jdouble instantiate(JNIEnv *env, jobject obj);
    jdouble uninstantiate(JNIEnv *env, jobject obj);
    void grabFocus();
    </code>
    The .cpp file:
    <code>
    #include "MyFunctions.h"
    #include <string.h>
    #include <stdlib.h>
    #include "stdafx.h"
    #include <iostream.h>
    jdouble canInstantiate(JNIEnv *env, jobject obj)
    printf("In canInstantiate!!");
    if (!instanceExists)
    printf("No instance exists!!");
    return (jdouble)0.0;
    else
    printf("An instance already exists!!");
    grabFocus();
    return (jdouble)1.0;
    jdouble instantiate(JNIEnv *env, jobject obj)
    printf("**In CPP: Instantiate!!\n");
    cout << "At start, env is: " << env << endl;
    cout << "At start, obj is: " << obj << endl;
    if (instanceExists == false)
    instanceExists = true;
    theJavaEnv = env;
    instanceObject = obj;
    theJavaEnv->GetJavaVM(&theJavaVM);
    cls = (theJavaEnv)->FindClass("TheMainClassOfTheJar");
    if (cls == 0) {
    fprintf(stderr, "Can't find Prog class\n");
    exit(1);
    mid = (theJavaEnv)->GetMethodID(cls, "grabFocusInJava", "(I)I");
    if (mid == 0) {
    fprintf(stderr, "Can't find grabFocusInJava\n");
    exit(1);
    printf("About to call grabFocusInJava\n");
    grabFocus();
    printf("CPP: After the grab focus command in instantiate!!\n");
    cout << "At end, env is: " << env << endl;
    cout << "At end, obj is: " << obj << endl;
    return 0.0;
    else
    printf("CPP: Finished Instantiate!!\n");
    return 1.0;
    jdouble uninstantiate(JNIEnv *env, jobject obj)
    printf("CPP: In uninstantiate!!\n");
    if (instanceExists == true)
    instanceExists = false;
    theJavaVM = NULL;
    instanceObject = NULL;
    printf("CPP: Finishing uninstantiate!!\n");
    return 0.0;
    else
    printf("CPP: Finishing uninstantiate!!\n");
    return 1.0;
    void grabFocus()
    printf("In CPP::GrabFocus!!\n");
    instanceObject = theJavaEnv->NewGlobalRef(instanceObject);
    cls = (theJavaEnv)->FindClass("CardFormatter");
    if (cls == 0) {
    fprintf(stderr, "Can't find Prog class\n");
    exit(1);
    printf("Got the cls id again!!\n");
    if (cls == 0)
    printf("IT'S INVALID!!\n");
    mid = (theJavaEnv)->GetMethodID(cls, "grabFocusInJava", "(I)I");
    if (mid == 0) {
    fprintf(stderr, "Can't find grabFocusInJava\n");
    exit(1);
    theJavaEnv->CallIntMethod(instanceObject, mid, 2);
    printf("Called grabFocusInJava\n");
    </code>
    thanks in advance

    Can I Call method on one JVM from another through a dll
    ...The rest of your question merely expands on your title.
    And the answer to that question is no.
    When you call a method you are executing a "thread of execution." A thread of execution exists only in a single process. It can not exist in another process.
    If the dll is doing some interesting things then you could call a method that sets a flag. Data can move between instances. But you would then have to have a thread in that different process monitoring that flag. And sharing data in a dll is not a normal process, so it would have to be coded appropriately.
    If all you want to do is set the current focus to the existing application, then that can be done with existing windows functionality. You don't need to do anything special in your dll. You can probably search these forums to find the exact code. If not there are countless examples in windows repositories (like MSDN) on how to do that.

  • Methods of One Class In Another

    Can I make the methods of one class work in another?

    Thank you to all who responded so quickly. I want to be able to get information from my JTextFields in one class and put it into the Film class parameters of the class below. The film class is a JavaBean.
        import java.io.*;
    class SerializeFilm {
      public static void main(String args[]) {
        String [] actors = { "Harrison Ford", "Jean Connery" };
        String name= "Indiana Jones";
        Film film = new Film("Indiana Jones", "Aventure", 1989, actors, 2.0, 90);
        try {
          FileOutputStream file = new FileOutputStream(name + ".ser");
          ObjectOutputStream output = new ObjectOutputStream(file);
          output.writeObject(film);
          output.flush();
          output.close();
          } catch (IOException ex) {
             ex.printStackTrace();
    }

  • Invoke overriden method in grandparent class(wth trivial example)

    Hi,can any one help? Please read the following trivial example
    class BaseA{
    public void showName(){
    System.out.println("This is BaseA");
    class BaseB extends BaseA{
    public void showName(){
    System.out.println("This is BaseB");
    class Child1 extends BaseB{
    public void showName(){
    System.out.println("This is Child1");
    public void showParentName(){
    super.showName();
    public void showGrandName(){
    //How can I invoke showName() method in grandparent class BaseA
    public class Test2{
    public static void main(String arg[]){
    Child1 obj1= new Child1();
    obj1.showName();
    obj1.showParentName();
    I remember I read a book that mentions how to get around this trouble,but it is really long time ago,can anyone help? a million of thanks

    There might be better way to this but might be below is also work
    class BaseA{
    public void showName(){
    System.out.println("This is BaseA");
    class BaseB extends BaseA{
    public void showName(){
    System.out.println("This is BaseB");
    public void showParentName(){
    super.showName();
    class Child1 extends BaseB{
    public void showName(){
    System.out.println("This is Child1");
    public void showParentName(){
    super.showName();
    public void showGrandName(){
    //How can I invoke showName() method in grandparent class BaseA
    super.showParentName();
    public class Test2{
    public static void main(String arg[]){
    Child1 obj1= new Child1();
    obj1.showName();
    obj1.showParentName();
    obj1.showGrandName();

  • Many Classes Vs Many Methods in one class

    Can any one tell me what are the advantages & disadvantages - and which is better?
    Having many methods (say about 15) in One class - about 10 doing various actions and not interrelated at all.
    Vs
    spliting the methods to be in their own classes, and instantiating them only when needed? Say in this case there could be about 10 classes thus created .
    Thanks
    Aarvi

    >
    I have got a chance to rewrite the existing code that
    has about 75 "unrelated" methods in one class. ( do
    not throw me out of this community now).
    When I said, these methods should be put in their own
    class based on their own functionality and can be
    loaded only when it is called for. The counter
    argument from the tech arch (!!) here is - "Why not
    have it in one class? It works now". The tech arch is
    a cobal type developer.
    Hate to repeat what was said above (given the source) but.....
    an object is not merely a collection of methods,
    So far you have referred only to the methods.
    Are there any data members?
    If no then all you have is a collection of methods. You can of course still break them up but doing so doesn't necessarily mean it will be better. But in terms of the "tech arch" the impact is minimal. That of course doesn't mean that testing isn't required.
    On the other hand if there is data then breaking them up would be based on how the data is used by the methods. As for why you would do that, the reason for the "tech arch" would be because the reason for using an OO language is so that one can have objects. And that 'class' is not an object.

  • If there are two synchronized methods in one class.

    If there are two synchronized methods in one class then what will be the beheviour of the threads accessing the methods.

    Synchronization is on objects, not methods or classes. A thread, entering a synchronized method, synchronizes on the object on which that method is called. Another thread, attempting to synchronize on that object, will be made to wait until the first thread releases it.

  • Is there any way to call methods of one view from another

    Hi experts,
    I am new to webdynpro.I am having some requirement in which I need to call methods of one view from some other view of same component .So is there any way to do this.

    Dear Pradeep,
    This will solve your problem......( plz 1st read everything ..)
    There are 2 views  :
    i) Mandatory Attributes ' view(V1)
    ii) Button' s  View..(V2)
    1. Create a method in Component Controller.( M1).
    2. Goto V2 . In the Action Handler method of Button , call method  M1 of component controller.
    3. Write your Code in M1 instead of  V2 method.
    4. Create an EVENT ( E1 ) in component controller.
    5. Fire this event  from M1 before executing Action Code.
    6. Now  Add the event handler method of  E1 in  V1 ( i.e. Mandatory attributes view. )   ..........clear????? .. set "METHOD TYPE" = Event Handler. instead of  Method.
    7. In this event handler method in V1 , write the "check_mandatory_attribute_view" method.
    8. use necessary flags..
    Regards ,
    Aditya.

  • Create one tables from 2 different tables

    Hi,
    How I can create one table from 2 different tables. Source tables have data and I want to include it in new table.
    I try this:
    create table NEW_ONE
    select * from OLD_ONE
    union
    select * from OLD_ONE2;
    But it didn't work correctly :/

    I don't have any error. This syntax create table NEW_ONE, but this table have columns only from OLD_ONE table :/ There aren't any column from OLD_ONE2 :/ Any suggestions?
    I don't forget about "as" in my query, only in this post.
    Edited by: tutus on Sep 8, 2008 6:36 AM

  • Invoking a method in WSDL file from client class

    Hi,
    I have got a WSDL file and I have to invoke certian methods from a client class from the WSDL file. What exactly should I do to invoke them from a Java standalone program /servlet/JSP. There is a sayHello() method in the WSDL. Please tell me how to invoke that method from client side. Aslo please let me know the jar files that are needed.
    Below is the WSDL file
    <?xml version="1.0" encoding="UTF-8"?>
    <wsdl:definitions targetNamespace="http://tutorial.com" xmlns:apachesoap="http://xml.apache.org/xml-soap" xmlns:impl="http://tutorial.com" xmlns:intf="http://tutorial.com" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:wsdlsoap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <!--WSDL created by Apache Axis version: 1.2.1Built on Jun 14, 2005 (09:15:57 EDT)-->
    <wsdl:message name="sayHelloResponse">
    </wsdl:message>
    <wsdl:message name="sayHelloResponse1">
    <wsdl:part name="sayHelloReturn" type="xsd:string"/>
    </wsdl:message>
    <wsdl:message name="addRequest">
    <wsdl:part name="a" type="xsd:int"/>
    <wsdl:part name="b" type="xsd:int"/>
    </wsdl:message>
    <wsdl:message name="sayHelloRequest">
    </wsdl:message>
    <wsdl:message name="addResponse">
    <wsdl:part name="addReturn" type="xsd:int"/>
    </wsdl:message>
    <wsdl:message name="sayHelloRequest1">
    <wsdl:part name="name" type="xsd:string"/>
    </wsdl:message>
    <wsdl:portType name="Hello">
    <wsdl:operation name="sayHello">
    <wsdl:input message="impl:sayHelloRequest" name="sayHelloRequest"/>
    <wsdl:output message="impl:sayHelloResponse" name="sayHelloResponse"/>
    </wsdl:operation>
    <wsdl:operation name="sayHello" parameterOrder="name">
    <wsdl:input message="impl:sayHelloRequest1" name="sayHelloRequest1"/>
    <wsdl:output message="impl:sayHelloResponse1" name="sayHelloResponse1"/>
    </wsdl:operation>
    <wsdl:operation name="add" parameterOrder="a b">
    <wsdl:input message="impl:addRequest" name="addRequest"/>
    <wsdl:output message="impl:addResponse" name="addResponse"/>
    </wsdl:operation>
    </wsdl:portType>
    <wsdl:binding name="HelloSoapBinding" type="impl:Hello">
    <wsdlsoap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/>
    <wsdl:operation name="sayHello">
    <wsdlsoap:operation soapAction=""/>
    <wsdl:input name="sayHelloRequest">
    <wsdlsoap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" namespace="http://tutorial.com" use="encoded"/>
    </wsdl:input>
    <wsdl:output name="sayHelloResponse">
    <wsdlsoap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" namespace="http://tutorial.com" use="encoded"/>
    </wsdl:output>
    </wsdl:operation>
    <wsdl:operation name="sayHello">
    <wsdlsoap:operation soapAction=""/>
    <wsdl:input name="sayHelloRequest1">
    <wsdlsoap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" namespace="http://tutorial.com" use="encoded"/>
    </wsdl:input>
    <wsdl:output name="sayHelloResponse1">
    <wsdlsoap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" namespace="http://tutorial.com" use="encoded"/>
    </wsdl:output>
    </wsdl:operation>
    <wsdl:operation name="add">
    <wsdlsoap:operation soapAction=""/>
    <wsdl:input name="addRequest">
    <wsdlsoap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" namespace="http://tutorial.com" use="encoded"/>
    </wsdl:input>
    <wsdl:output name="addResponse">
    <wsdlsoap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" namespace="http://tutorial.com" use="encoded"/>
    </wsdl:output>
    </wsdl:operation>
    </wsdl:binding>
    <wsdl:service name="HelloService">
    <wsdl:port binding="impl:HelloSoapBinding" name="Hello">
    <wsdlsoap:address location="http://localhost/WebService1/services/Hello"/>
    </wsdl:port>
    </wsdl:service>
    </wsdl:definitions>
    Thanks in advance
    Prashanth

    Hi.
    Please put this line in the google search engine "Invoking java web service" u will get lots of the links.
    Sanjay Kumar Gupta
    [email protected]

  • Referencing a method in one class from a constructor in another?

    Hi,
    I'm not sure whether this is a simple question or not, but instead of rewriting the method in another class, is there a way that I can reference that method, eg:
    public int getTitleCode() {
            return titleCode;  }within the constructor of another class. I don't want to use inheritance with this because it would change all my existing contructors.
    Any ideas how to do this, or is it just simpler to add the method to both classes?
    Many thanks!

    Hi,
    I'm trying to use a method, defined in Class A, within one of the constructors in Class B. Class B object represents a copy of the output of Class A, with the addition of a few extra methods.
    Therefore to represent the details correctly in the saved text file for class B, I need to call a method from class A to save the text file for class B correctly.
    Class B saves a file with a reference number unique to that class, plus a reference number that is also saved in the text file for class A.
    I can achieve the correct result for the above by having the same method in both classes, but I just wondered whether instead of this I could in fact call the method from class A in the constructor for class B. With the following code,
        referenceNumber = refNum;
            titleReferenceNumber = titleRefNum;
            titleRefNum = titles.getTitleCode();
        }I just get a 'nullpointerexception' when I try to run this in the main class.
    Any help or advice appreciated!

  • How to call main method in one class from another class

    Suppose i have a code like this
    class Demo
    public static void main(String args[])
    System.out.println("We are in First class");
    class Demo1
    public static void main(String args[])
    System.out.println("We are in second class");
    In the above program how to call main method in demo calss from Demo1 class......???????

    No, i dont know how to call other than main methods from other classes
    And one more doubt i have i.e. Like in C can we see the execution of the program like how the code is being compiled step by step and how the value of the variable changes from step to step like(Add Watch).........

  • Invoke a Method of a Class

    Hello !
    Below I am giving my Problem.....
    I hav a List Class Named as : DepartmentList and a method called getInstance()
    Now if that is a class then i must call it as :
    DepartmentList deptInst=new DepartmentList()
    then method call as : deptInst.getInstance()
    But unfortuntly,
    now I've a String strClass="DepartmentList";
    and String strMethod="getInstance";
    I've to invoke that method.. How ???
    Plz give the solution..
    Hint: Check forName(..) to get the appropiate Class then it's method... But unable to invoke that method..
    Thanks !
    BS

    You can get a class using the Class.forName method like this:
    Class clazz = Class.forName ("DepartmentList");Note that you have to add any package names to this name as well or else it will not find the class.
    Then there's a getMethod method available that takes the name of the method and any number of parameter classes. In your case this would be:
    Method meth = clazz.getMethod ("getInstance");you can then call invoke on this method object. See the javadoc for what parameters you exactly need, if any :)
    good luck !

  • Need call a method of one iview from another iview

    Hi,
    There are 2 iviews in a component.
    1) FirstView - contains abc() method & xyz() methods
    2) SecondView (a popup) - asdf() method
    i want to call abc() method from asdf() method. i.e. i want to call a method of the firstview from the secondview.
    Note:
    1) i couldn't able to copy the code of abc() method to component controller, as it has the code which uses (iview) local attributes (this can be done by context mapping) & main reason is from the method it calls the xyz() method of the same view (again i couldn't call a method of iview from component controller).
    2) firstView contain 5 tabs, i want to be in the same tab from which secondview (popup) was called, if i use fire plugs between both view, the current tab will be chnaged (i suppose, not sure).
    3) can we use event handlers, if yes how can we do that.
    Please provide a better solution for calling a method of view from another view.
    Thanks
    Maha
    Edited by: Maha Hussain on Jan 13, 2009 12:40 PM

    Hi Maha,
    It is better to have such methods in the component controller to make it reusable and avoid writing same code again and again.
    You can have that method in component controller and call that method on click on a button from Iview1 and can pass the parameters in the mthgod only.
    for example.
    Say Method abc() which is currently in Iview1 and you are passing values from context say aa bb cc to the method now what i am suggesting is
    have that method abc(String aa, String bb, String cc) ;
    and call it on click on button in Iview1 and pass the required parameters.
    Hope this will help
    Regards
    Narendra

  • One Cube from 3 Different ODS's

    Is it possible to create a single cube from three different ODS's , the ODS's have same characteristics but different key figures.
    Thanks

    As you mentioned , that all your ODS have the same characteristics you could create seperate update rules for all 3 ODS Objects..
    The difference will be only in the Key Figure update rule where only the Key figure present in the ODS will be mapped to the cube and the rest will be blank meaning no update..
    Hope this helps..
    ashish.

Maybe you are looking for

  • Can VGA transmit high-def resolution?

    I'm planning on buying the Mini-DVI to VGA adapter to connect my macbook to my Samsung HDTV (LN-S4095D). The TV supports resolutions up to 1920x1080 through its VGA input. However, after reading up a little on VGA cables (http://en.wikipedia.org/wiki

  • Clustering using mod_wl_ohs plugin

    Hello all. I am currently trying to determine the best architecture for use within the company. and i need help. We currently have a front end which is publicly accessible which goes through a middleware and then calls a webservice that sits on weblo

  • Newbie looking for E-MU Manual

    Have 200+ DAT tapes that I would like to archive to computer (internal or external) storage but recognize this would need to be via USB. Have capability to burn CD-Rs which could then be ripped to storage but this would be a huge task with wasted ste

  • What is max size of slicer values in Power View on SharePoint?

    I have Power View on SharePoint 2013 and OLAP Cube on SQL Server 2014 solution. I should have 1000 values in DimCity, but not all are available in slicer. Why? What is max value? Kenny_I

  • Foreign Keys in Primary Key Class

    I am a newbie on toplink. I am getting an error when i run ejbc against the jar file with EJB2.0. One of the primary key classes two primary keys and both are foreign Keys to other tables. Primary Key class looks like this: public class LcaCyberzoneA