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.

Similar Messages

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

  • 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.

  • 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.

  • 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?

  • Problem calling java method from c

    Hi ,
    I'm trying to call a java method from a C program. it gives no error during compilation as well as building the application. but when i tried to create the JVM by running my application it pops up the message "The application failed to start because jvm.dll was not found. Re-installing the application may fix the problem." I tried out setting all the environment variables to include the jvm.dll(PATH set to c:\j2sdk1.4.2_05\bin;c:\j2sdk1.4.2_05\jre\bin). Still got the same message. Then i re-installed java platform once more. Even now i get the same error. I have more than one jvm.dll at locations jre\bin\client and server, oracle has some jvm.dll . Will that be a problem? if so can i remove those? which of them should be removed and how?
    The code i'm using is
    #include <stdio.h>
    #include <jni.h>
    #include <windows.h>
    //#pragma comment (lib,"C:\\j2sdk1.4.2_05\\lib\\jvm.lib")
    JavaVM jvm; / Pointer to a Java VM */
    JNIEnv env; / Pointer to native method interface */
    JDK1_1InitArgs vm_args; /* JDK 1.1 VM initialization requirements */
    int verbose = 1; /* Debugging flag */
    FARPROC JNU_FindCreateJavaVM(char *vmlibpath)
    HINSTANCE hVM = LoadLibrary("jre\\bin\\server\\jvm.dll");
    if (hVM == NULL)
    return NULL;
    return GetProcAddress(hVM, "JNI_CreateJavaVM");
    void main(int argc, char **argv )
    JavaVM jvm = (JavaVM )0;
    JNIEnv env = (JNIEnv )0;
    JavaVMInitArgs vm_args;
    jclass cls;
    jmethodID mid;
    jint res;
    FARPROC pfnCreateVM;
    JavaVMOption options[4];
    // jint (__stdcall pfnCreateVM)(JavaVM *pvm, void **penv, void *args) = NULL;
    options[0].optionString = "-Djava.compiler=NONE"; /* disable JIT */
    options[1].optionString = "-Djava.class.path=c:/j2sdk1.4.2_05/jre/lib/rt.jar"; /* user classes */
    options[2].optionString = "-Djava.library.path=lib"; /* set native library path */
    options[3].optionString = "-verbose:jni"; /* print JNI-related messages */
    /* Setup the environment */
    vm_args.version = JNI_VERSION_1_4;
    vm_args.options = options;
    vm_args.nOptions = 4;
    vm_args.ignoreUnrecognized = 1;
    JNI_GetDefaultJavaVMInitArgs ( &vm_args );
    pfnCreateVM = JNU_FindCreateJavaVM("jre\\bin\\server\\jvm.dll");
    res = (*pfnCreateVM)(&jvm,(void **) &env, &vm_args );
    // res = JNI_CreateJavaVM(&jvm,(void **) &env, &vm_args );
    /* Find the class we want to load */
    cls = (*env)->FindClass( env, "InstantiatedFromC" );
    if ( verbose )
    printf ( "Class: %x" , cls );
    /*jvm->DestroyJavaVM( );*/
    Could anyone help me solve this problem as early as possible, bcoz i'm in an urge to complete the project.
    Thanks in advance.
    Usha.

    You either have to add to the system path of where is your jvm.dll is located or explicitly link to jvm.dll call GetProcAddress to obtain the address of an exported function in the DLL.

  • 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!

  • Problem calling Java method from JavaScript in JSP / ADF

    Hi all,
    In my JavaScript onMouseUp() function, I need to call a method on my Java backing bean. How is this done? Info on the web indicates a static Java method can be called by simply "package.class.staticMethod(...)". but when I put the statement
    "jsf.backing.GlobalRetriever.createBasemap(affectedLayer);"
    I get an error message "jsf is undefined".
    The functionality I'm trying to get is: I have a custom slider control and based on its value, I want to call oracle map viewer specifying a map extent of the (current extent / slider value) to do a zoom in/out. In addition, the slider uses a onMouseMove() function to change the size of the image display so it looks like a dynamic zoom in/out.
    Please assist or let me know if I can provide some additional information. Thanks in advance.
    Jim Greetham

    No. The Java and Javascript in a Faces application are really working in two different universes.
    Java is running on the server. It generates HTML (and sometimes even Javascript) and sends that to the client machine. That's where all your backing beans are.
    Javascript runs directly in the browser. There's no way anything on the server can have access to anything you define in Javascript, unless you explicitly send that information back to the server, either via standard form submission (which only works when someone presses a "Submit" button) or via an Ajax-type call. So otherwise, nothing you define in Javascript will ever be available to a backing bean.

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

  • Re: problem calling a method from another class

    This line here:
    app.computeDiscount(ord,tentativeBill);... You are not capturing the returned amount.
    double d = app.computeDiscount(ord,tentativeBill);

    what kind of problem r u facing?
    plz highlight the code where u r facing the problem

Maybe you are looking for