javaswingsyntaxserverjava-server

Call from a main of one class, a main method of another class


I have two bearing classes - a GUI one and Server. They both have main() methods. When a 'connect' button (from class GUI) is clicked I want to start up all the processes in class Server, by starting from its main() function. Am I able to do that at all, is there a way to avoid it?

I've tired to: - Delete the main(String[] args) part of the Server class, rename it initServer and then through GUI to say

Server kb = new Server();
kb.initServer();`

That is all I have right now, when clicked the Connect button its event takes place but all neither of the Server checks show up, in the command line.


Solution

  • Are you looking for something like this?

    Test.java

    public class Test {
        private void run() {
            new Test2();
        }
    
        public static void main(String[] args) {
            Test t = new Test();
            t.run();
        }
    }
    

    Test2.java

    public class Test2 {
        Test2() {
            System.out.println("Hi");
        }
    }
    

    Where when the function run() is executed in the first class, it executes the second class? In your case you would do this with an ActionListener and the second class would start your server

    But to answer the question properly, How can you call the main from another class?, you can do it like this:

    Test.java

    public class Test {
        private void run() {
            new Test2().main(null);
        }
    
        public static void main(String[] args) {
            Test t = new Test();
            t.run();
        }
    }
    

    Test2.java

    public class Test2 {
        public static void main(String[] args) {
            System.out.println("Hi");
        }
    }