简体   繁体   中英

Instance “Main” Method Not Running When Called from Another Class

I'm learning Java and experimenting with Javafx in netbeans.

I am running the sqlite tutorial here: http://www.tutorialspoint.com/sqlite/sqlite_java.htm

When set up as a lone-file it works fine of course.

I'm setting it up in a test project "testDB" and for some reason when I initiate the class the class itself is recognized, but main() is not running.

Here is the testdb file itself:

testDB.java:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package sqlitetest;

import java.sql.*;

/**
 *
 */
public class testDB {

    public static void main(String args[]) {

        //THESE STEPS ARE ON NOT RUNNING (compiles without errors)

        System.out.println("testing");
        Connection c = null;
        try {
            Class.forName("org.sqlite.JDBC");
            c = DriverManager.getConnection("jdbc:sqlite:test.db");
        } catch (Exception e) {
            System.err.println(e.getClass().getName() + ": " + e.getMessage());
            System.exit(0);
        }
        System.out.println("Opened database successfully");    

    }

    public void makeStuff(){

    }

}

sqlitetest.java

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package sqlitetest;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

/**
 *
 */
public class Sqlitetest extends Application {

    @Override
    public void start(Stage stage) throws Exception {
        Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));

        Scene scene = new Scene(root);


        stage.setScene(scene);
        stage.show();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        testDB test = new testDB();
        test.makeStuff();
        launch(args);
    }

}

I think you are getting confused between a constructor and a main method.

  • A main method is only invoked when you start the JVM, running that specific class (or if you invoke it explicitly elsewhere).
  • A constructor is invoked when you create an instance of the class, like you are doing here.

In testdb , change:

public static void main(String args[]) {

to

public testdb() {

Alternatively, invoke testdb.main(args) (or with some other parameter) in Sqlitetest.main .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM