Calling a method from a different class?

Ok..
I been trying for hours... but im stumped.
How can I get this to work?
(Note: I cut this code down from over 600+ lines of code.. I left in a REALLY raw framework that shows where the basic problem is.)
public class Client extends JPanel implements Runnable {
// variable declarations...
    Socket connection;
    BufferedReader fromServer;
    PrintWriter toServer;
    public Client(){
// GUI creation...
// Create the login JFrame
    Login login = new Login()
    public void connect(){
    try {
            //Attempt to connect to the server
            connection = new Socket(ip,port);
            fromServer = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            toServer = new PrintWriter(connection.getOutputStream());
            //Launch a thread here to read incoming messages from the server
            //so I dont block on reading
            new Thread (this).start();
    } catch (Exception e) {
        e.printStackTrace();
    public void run(){
        // This keeps reading lines from the server
        String s;
        try {
            //Read messages sent from the server - add them to chat window
            while ((s=fromServer.readLine()) != null) {
            txtChat.append(s);
        } catch (Exception e) {}
    public static void main(String args[]){
        // some init frame stuff
        frame = new JFrame();
        frame.getContentPane().add(new Client(),BorderLayout.CENTER);
     frame.setVisible(true);
class Login extends JFrame {
    JPanel pane;
    public Login() {
     super("Login");
     pane = new JPanel();
     JButton cmdConnect = new JButton("Connect");
        pane.add(cmdConnect);
     setContentPane(pane);
     setSize(300,300);
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     cmdConnect.addActionListener(new ActionListener(){
         public void actionPerformed(ActionEvent ae){
          // I want to connect to the server when this button is pressed.
          // How can I call the connect method in the Client class?
}

Your posted code shows Login as an inner class. So one way to solve your problem is.
1. Make an instance variable to hold the instance. For example, after "PrintWriter toServer;" add "private Client client;"
2. In the Client constructor, add a line "client = this;"
3. In the Login actionPerformed(), use "client.connect();"
Another way is to have Login keep a reference to the Client that created it.
1. Add an instance variable to Login "private Client client;"
2. Change the Login constructor "public Login(Client c) {"
3. Add a line in the constructor "client = c;"
4. In the actionPerformed() "client.connect();"

Similar Messages

  • Problems calling a method from a different class

    Like many programmers, I'm having a go at making my own chat room. All has been going well so far, however I am having trouble calling the method which connects the client to the server, from the method which actually starts the server.
    The method for starting the server:
    public static void serverStart () throws IOException {
            new Thread () {
            public void run() {
                try {
                    ServerSocket serverSock = new ServerSocket (client.serverPort);
                while (true) {
                    Socket serverClient = serverSock.accept ();
                    ChatHandler handler = new ChatHandler(serverClient);
                    handler.start ();
                } catch (IOException ex) {     
                    connectTo.handleIOException(ex);     
            }.start();
            try {
                connectTo.start();
            } catch (IOException ex) {
                connectTo.handleIOException(ex);
        }The part of interest is the "connectTo.start()" line, as this is the one which calls a method in the class connectToMethod which tells the client to connect to this newly started server. Now for the client connection code:
    public synchronized void start () throws IOException {
          if (listener == null) {
              Socket socket = new Socket (client.serverAddr, client.serverPort);
              try {
                  dataIn = new DataInputStream
                          (new BufferedInputStream (socket.getInputStream ()));
                  dataOut = new DataOutputStream
                          (new BufferedOutputStream (socket.getOutputStream ()));
              } catch (IOException ex) {
              socket.close ();
              throw ex;
          listener = new Thread (this);
          listener.start ();
      }Now when the server starts, it should automatically start the connection method "start()" and connect to itself. However I am getting a NullPointerException error at the line "connectTo.start();" from the server code. The server and connection client actually work separately, just not when I try to connect from the server itself. I have tried a few ways of getting around this problem, all without success. If anyone could give some input on what might be wrong, or a possible way to fix it, I'd be very grateful.

    Sorry, connectTo comes from:
    connectToMethod connectTo = new
    connectToMethod();
    That doesn't necessarily mean this variable reference is the same one as in the code where the NullPointerException was thrown though.
    Or the exception was thrown inside the start() method. The runtime isn't lying to you. You have a null reference (pointer) where it says you do.

  • Calling a method from a super class

    Hello, I'm trying to write a program that will call a method from a super class. This program is the test program, so should i include extends in the class declaration? Also, what code is needed for the call? Just to make things clear the program includes three different types of object classes and one abstract superclass and the test program which is what im having problems with. I try to use the test program to calculate somthing for each of them using the abstract method in the superclass, but its overridden for each of the three object classes. Now to call this function what syntax should I include? the function returns a double. Thanks.

    Well, this sort of depends on how the methods are overridden.
    public class SuperFoo {
      public void foo() {
         //do something;
      public void bar(){
         //do something
    public class SubFoo extends SuperFoo {
       public void foo() {
          //do something different that overrides foo()
       public void baz() {
          bar(); //calls superclass method
          foo(); //calls method in this (sub) class
          super.foo(); //calls method in superclass
    }However, if you have a superclass with an abstract method, then all the subclasses implement that same method with a relevant implementation. Since the parent method is abstract, you can't make a call to it (it contains no implementation, right?).

  • Calling a method in a different class?

    How do you call a method from a differnt class into the class you are working on?

    Class and method were just generic names. You should insert the names of your classes and methods.
    class OtherClass {
        public static void one() {
            System.out.println("Static method")l;
        public void two() {
            System.out.println("Non-static method");
    class MainClass {
        public static void main(String[] args) {
            OtherClass.one();
            OtherClass oc = new OtherClass();
            oc.two();
    }

  • Need help calling a method from an immutable class

    I'm having difficulties in calling a method from my class called Cabin to my main. Here's the code in my main              if(this is where i want my method hasKitchen() from my Cabin class)
                        System.out.println("There is a kitchen.");
                   else
                        System.out.println("There is not a kitchen.");
                   }and here's my method from my Cabin class:public boolean hasKitchen()
         return kitchen;
    }

    You should first have an instance of Cabin created by using
       Cabin c = ....
       if (c.hasKitchen()) {
         System.out.println("There is a kitchen.");
       } else {
            System.out.println("There is not a kitchen.");
       }

  • Calling a method from an abstract class in a seperate class

    I am trying to call the getID() method from the Chat class in the getIDs() method in the Outputter class. I would usually instantiate with a normal class but I know you cant instantiate the method when using abstract classes. I've been going over and over my theory and have just become more confused??
    Package Chatroom
    public abstract class Chat
       private String id;
       public String getID()
          return id;
       protected void setId(String s)
          id = s;
       public abstract void sendMessageToUser(String msg);
    Package Chatroom
    public class Outputter
    public String[] getIDs()
         // This is where I get confused. I know you can't instantiate the object like:
            Chat users=new Chat();
            users.getID();
    I have the two classes in the package and you need to that to be able to use a class' methods in another class.
    Please help me :(                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    I have just looked over my program and realised my class names are not the most discriptive, so I have renamed them to give you a clearer picture.
    package Chatroom
    public abstract class Chatter
    private String id;
    public String getID()
    return id;
    protected void setId(String s)
    id = s;
    I am trying to slowly build a chatroom on my own. The Chatter class is a class that will be used to represent a single logged in user and the user is given an ID when he logs in through the setId and getID() methods.
    package Chatroom;
    import java.util.Vector;
    public class Broadcaster
    private Vector<Chatter> chatters = new Vector<Chatter>();
    public String[] getIDs()
    // code here
    The Broadcaster class will keep a list of all logged-in users keeps a list of all the chats representing logged-in users, which it stores in a Vector.I am trying to use the getIDs() method to return an array of Strings comprising the IDs of all logged-in users, which is why im trying to use the getID() method from the Chat class.
    I apologise if I come across as clueless, it's just I have been going through books for about 4 hours now and I have just totally lossed all my bearings

  • How to call a method from a separate class using IBAction

    I can't work out how to call a method form an external class with IBAction.
    //This Works 1
    -(void)addCard:(MyiCards *)card{
    [card insertNewCardIntoDatabase];
    //This works 2
    -(IBAction) addNewCard:(id)sender{
    //stuff -- I want to call [card insertNewCardIntoDatabase];
    I have tried tons of stuff here, but nothing is working. When i build this I get no errors or warnings, but trying to call the method in anyway other that what is there, i get errors.

    Can you explain more about what you are trying to do? IBAction is just a 'hint' to Interface Builder. It's just a void method return. And it's unclear what method is where from your code snippet below. is addNewCard: in another class? And if so, does it have a reference to the 'card' object you are sending the 'insertNewCardIntoDatabase' message? Some more details would help.
    Cheers,
    George

  • Can we call a method from a adapter class?

    Hi
    I have added KeyAdapter class to a textfield now i want to call a method in the outer class from inside the adapter class. I tried but its showing some error,
    public class A
    A()
    TF1.addKeyListener(new KeyAdapter()
    public void keyReleased(KeyEvent e)
    A a=new A();
    ec.chkSalary();                    
    chkSalary()
    can i call the method like this?

    yeah.. i got it.. i just passed that KeyEvent object to the method
    but i did declare that as a char in that method like,
    chkSalary(e) // e is the KeyEvent reference
    and the method is
    chk(char e);
    thats it.
    thank you yaar.

  • Using main class's methods from a different class in the same file

    Hi guys. Migrating from C++, hit a few snags. Hope someone can furnish a quick word of advice here.
    1. The filename is test.java, so test is the main class. This code and the topic title speak for themselves:
    class SomeClass
         public void SomeMethod()
              System.out.println(test.SomeOperation());
    public class test
         public static void main(String args[])
              SomeClass someObject = new SomeClass();
              someObject.SomeMethod();
         public static String SomeOperation()
              return "SomeThing";
    }The code works fine. What I want to know is, is there some way to use test.SomeOperation() from SomeClass without the test.?
    2. No sense opening a second topic for this, so second question: Similarly, is there a good way to refer to System.out.println without the System.out.? Like the using keyword in C++.
    Thanks.

    pfiinit wrote:
    The code works fine. What I want to know is, is there some way to use test.SomeOperation() from SomeClass without the test.?Yes you can by using a static import, but I don't recommend it. SomeOperation is a static method of the test class, and it's best to call it that way so you know exactly what your code is doing here.
    2. No sense opening a second topic for this, so second question: Similarly, is there a good way to refer to System.out.println without the System.out.? Like the using keyword in C++.Again, you could use static imports, but again, I don't recommend it. Myself, I use Eclipse and set up its template so that when I type sop it automatically spits out System.out.println(). Most decent IDE's have this capability.
    Also, you may wish to look up Java naming conventions, since if you abide by them, it will make it easier for others to understand your code.
    Much luck and welcome to this forum!

  • Calling a method in a different class. PLEASE HELP!!

    For my java class I am writing a program on exceptions. Bascially this is the skeleton of the program that I have written. The program is too long to type in this messgae.
    class ryan
    includes main
    suberror2 is called from here
    suberror 3 is called from here
    class BaseRT
    includes method basemakeserror
    class SubMS extends BaseRT
    basemakeserror is called from here(The error I get is with this line)
    includes method subCallsError
    includes method subError2
    includes method subEoor3
    Here is my problem: Whenever I run my program I keep getting an error that says baseMakesError1 in Ryan.BaseRT cannot be applied to Ryan.SubRT. Can anyone help me and tell me what I'm doing wrong. I would really appreciate it.

    Odd, you've extended the class, so there should be no problem in calling the method. We would need to see more, such as the implementation of the method (i.e. what it does) to find out more, but in theory, you should have no problem. Did you declare the method public?

  • How can i call a main method  from a different class???

    Plzz help...
    i have 2 classes.., T1 and T2.. Tt2 is a class with a main method....i want to call the main method in T2......fromT1..is it possibl..plz help

    T2.main(args);

  • How to Call a method from a separate class...?

    Hi there...
    I have a class name HMSCon which has a method named con...
    method con is the one the loads the jdbc driver and establishes the connection....Now!I have a separate class file named TAQueries,this is where i am going to write my SQL Statements...any idea how to use my variables from HMSCon to my TAQueries class???
    here's my code:
    public class HMSCon{
    public static void con(){
    try{
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    String url="jdbc:odbc:;DRIVER=Microsoft Access Driver (*.mdb);DBQ=" +
    "E:/samer/HardwareMonitoringSystem/src/hms/pkg/hmsData.mdb";
    Connection cn = DriverManager.getConnection(url,"Admin", "asian01");
    }catch(Exception s){
    System.err.print(s);}
    here's my seperate class file TAQueries,i put an error message below..
    class TAInfoQueries{
    public void insertNewTA(String TAID,String Fname,String Mname, String Lname,String Age,
    String Bdate,String Haddress,String ContactNo){
    // Statement stmt=cn.createStatement(); ERROR: Cannot find symbol cn.
    // stmt.executeUpdate("INSERT INTO TechnicalAssistants VALUES('sdfas','sdfsdf','sdfdsf','sdfdsf',3,04/13/04,'asdf','asdfsdf')");
    // stmt.close();
    }

    You can try the below code, but it's a bad idea to use staitc member for connection:(
    public class HMSCon{
    static Connection cn;
    static{
    con();
    public static void con(){
    try{
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    String url="jdbc:odbc:;DRIVER=Microsoft Access Driver (*.mdb);DBQ=" +
    "E:/samer/HardwareMonitoringSystem/src/hms/pkg/hmsData.mdb";
    cn = DriverManager.getConnection(url,"Admin", "asian01");
    }catch(Exception s){
    System.err.print(s);}
    here's my seperate class file TAQueries,i put an error message below..
    class TAInfoQueries{
    public void insertNewTA(String TAID,String Fname,String Mname, String Lname,String Age,
    String Bdate,String Haddress,String ContactNo){
    // Statement stmt=HMSCon.cn.createStatement(); ERROR: Cannot find symbol cn.
    // stmt.executeUpdate("INSERT INTO TechnicalAssistants VALUES('sdfas','sdfsdf','sdfdsf','sdfdsf',3,04/13/04,'asdf','asdfsdf')");
    // stmt.close();
    }

  • Problem Using toString method from a different class

    Hi,
    I can not get the toString method to work from another class.
    // First Class Separate file MyClass1.java
    public class MyClass1 {
         private long num1;
         private double num2;
       public MyClass1 (long num1, double num2) throws OneException, AnotherException {
            // Some Code Here...
        // Override the toString() method
       public String toString() {
            return "Number 1: " + num1+ " Number 2:" + num2 + ".";
    // Second Class Separate file MyClass2.java
    public class MyClass2 {
        public static void main(String[] args) {
            try {
               MyClass1 myobject = new MyClass1(3456789, 150000);
               System.out.println(myobject);
             } catch (OneException e) {
                  System.out.println(e.getMessage());
             } catch (AnotherException e) {
                  System.out.println(e.getMessage());
    }My problem is with the System.out.println(myobject);
    If I leave it this way it displays. Number 1: 0 Number 2: 0
    If I change the toSting method to accept the parameters like so..
    public String toString(long num1, double num2) {
          return "Number 1: " + num1 + " Number 2:" + num2 + ".";
       }Then the program will print out the name of the class with some garbage after it MyClass1@fabe9. What am I doing wrong?
    The desired output is:
    "Number 1: 3456789 Number 2: 150000."
    Thanks a lot in advance for any advice.

    Well here is the entire code. All that MyClass1 did was check the numbers and then throw an error if one was too high or too low.
    // First Class Separate file MyClass1.java public class MyClass1 {
         private long num1;
         private double num2;
         public MyClass1 (long num1, double num2) throws OneException, AnotherException {              
         // Check num2 to see if it is greater than 200,000
         if (num2 < 10000) {
                throw new OneException("ERROR!:  " +num2 + " is too low!");
         // Check num2 to see if it is greater than 200,000
         if (num2 > 200000) {
                throw new AnotherException ("ERROR!:  " +num2 + " is too high!");
         // Override the toString() method
         public String toString() {
              return "Number 1: " + num1+ " Number 2:" + num2 + ".";    
    // Second Class Separate file MyClass2.java
    public class MyClass2 {
        // Main method where the program begins.
        public static void main(String[] args) {
            // Instantiate first MyClass object.
            try {
               MyClass1 myobject = new MyClass1 (3456789, 150000);
               // if successful use MyClass1 toString() method.
               System.out.println(myobject);
                         // Catch the exceptions within the main method and print appropriate
                         // error messages.
             } catch (OneException e) {
                  System.out.println(e.getMessage());
             } catch (AnotherException e) {
                  System.out.println(e.getMessage());
             }I am not sure what is buggy. Everything else is working fine.

  • How to call java method from C ?

    Hello,
    I try to call a native method from java which calls java method from the same class. Exception (noSuchMethodError) is thrown. Any ideas?
    Thanx in advance !
    here is the source of the native method :
    JNIEXPORT jint JNICALL Java_TestDll_Proc_1Mul_1Int_1Var_1Var_1Stdcall (JNIEnv * env, jclass jcl, jint jarg1, jint jarg2) {
    int arg1;
    int arg2;
    int arg3;
    jint res;
    char * ch = "test";
    jfieldID fid;
    jmethodID mid;
    int (* procedure) (int *, int * ,int *);
    int mch;
    arg1 = (int )jarg1;
    arg2 = (int )jarg2;
    procedure = GetProcAddress(libraryHandle,"Proc_Mul_Int_Var_Var_Stdcall");
    procedure(&arg1,&arg2,&arg3);
    res = (jint) arg3;
    printf("(*env)->GetMethodID(env, jcl, \"test\", \"()V\");\n");
    mid = (*env)->GetMethodID(env, jcl, "test", "()V");
    printf("(*env)->CallVoidMethod(env, jcl, mid);\n");
    (*env)->CallVoidMethod(env, jcl, mid);
    return res;
    here is the source of the java file:
    public class TestDll {
    static {
    System.loadLibrary("testdllwrap");
    System.out.println("java: Library testdllwrap.dll loaded");
    public TestDll() {
    public native int Proc_Mul_Int_Var_Var_Stdcall(int jarg1, int jarg2);
    public void test() {
    System.out.println("java: test()");
    public static void main(String[] args) {
    TestDll access = new TestDll();
    int a = 5;
    int b = 6;
    int c = 0;
    System.out.println("Calling Proc_Mul_Int_Var_Var_Stdcall");
    c = access.Proc_Mul_Int_Var_Var_Stdcall(a,b);
    System.out.println("Java Result = " + c);

    Something is wrong with the code you posted here.
    Since your native method is not static, it should have the jobject instance as a parameter in the function prototype, not a jclass. Also, you should be calling CallObjectMethod with a jobject, not jclass.
    Check out Jace at http://jace.reyelts.com/jace.
    To call the java method you would do:
    JNIEXPORT jint JNICALL Java_TestDll_Proc_1Mul_1Int_1Var_1Var_1Stdcall
    (JNIEnv * env, jobject jTestDll, jint jarg1, jint jarg2) {
      TestDll testDll( jTestDll );
      testDll.test();
    }God bless,
    -Toby Reyelts

  • How do I call an Application Module method from a EntityImpl class?

    Guys and Gals,
    Using Studio Edition Version 11.1.1.3.0.
    I've got a price update form, that when submitted, takes the part numbers and prices in the form and updates the corresponding Parts' price in the Parts table. Anytime this Parts view object's ReplacementPrice attribute is changed, an application module method needs to be called which updates a whole slew of related view objects. I know you can modify view objects via associations (How do I call an Application Module method from a ViewObjectImpl class? but that's not what I'm trying to do. These AppModuleImpl methods are the hub for all price updates, as many different operations may affect related pricing (base price lists, price buckets, etc) and hence, call the updatePartPricing(key) method.
    For some reason, the below code does not call / run / activate the application module's method. The AppModuleDataControl exists and recordPartHistory(key) is registered and public. At runtime, the am.<method> code is simply ignored, and as a weird side-effect, I cannot navigate out of my current page flow.
      public void setReplacementPrice(Number value)
        setAttributeInternal(REPLACEMENTPRICE, value);
        AppModuleImpl am = (AppModuleImpl)this.getDBTransaction().findApplicationModule("AppModuleDataControl");
        Key key = new Key(new Object[]
            { getPartNumber() });
        am.recordPartHistory(key);  // AppModuleImpl method which records pricing history
        am.updatePartPricing(key); // AppModuleImpl method which updates a whole slew of related pricing tables
      }Any ideas?

    Thanks Timo.
    Turns out the code provided was correct, but the AppModuleImpl method being called was not. A dependent ViewObject wasn't returning the row I was expecting. I then tried to perform some operations on that row, which in turn ... just stopped everything, but didn't give me an error.
    It was the lack of the error that threw me off. I had never messed with calling an AppModuleImpl method from the EntityImpl so I assumed that's what was messing up.
    You are correct. It is available from the ViewRow, but I thought it better to put it in the EntityImpl. This method will be called every time the replacement cost is modified. If I didn't put it in the EntityImpl, I'd have to remember to call it every time a replacement cost changed.

Maybe you are looking for