我有一个名为databaseConnection的类,我想在应用程序启动时启动/执行它,似乎我应该从start方法(我称之为MainApp)调用它,但我似乎无法找到正确的这样做的方式,因此我的问题
我认为这很容易,但我真的无法得到它
的DatabaseConnection:
package albertheijnhandterminal;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.ResourceBundle;
/**
*
* @author Stanly
*/
public class databaseConnection {
private static String dbURL = "jdbc:derby://localhost:1527/AlbertHeijnHandterminal;create=true;user=StanlySuijk;password=hoi55455";
private static Connection connection = null;
private static Statement statement = null;
public static void main(String[] args) {
createConnection();
//insertUsers("");
//selectUsers();
//shutdown();
}
private static void createConnection() {
try {
Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();
//Get a connection
connection = DriverManager.getConnection(dbURL);
} catch (Exception exception) {
}
}
}
MainApp:
package albertheijnhandterminal;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import static javax.management.remote.JMXConnectorFactory.connect;
/*
1
9 @author Stanly
9
9
*/
public class MainApp extends Application {
public static FrameController theFrameController = null;
static StackPane displayPane;
public static Connection connection = null;
public static Statement statement = null;
public static PreparedStatement preparedStatement = null;
public static ResultSet resultSet = null;
@Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("Frame.fxml"));
Scene scene = new Scene(root);
stage.setTitle("Albert Heijn Handterminal");
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
我只编程了大约6个月,所以如果你看到我的代码中有一些改进,那将是值得赞赏的。
答案 0 :(得分:5)
如果你的应用程序是MainApp
类,那么该类应该有main方法。然后你应该做以下几点。
public static void main(String[] args) {
databaseConnection db = new databaseConnection ();
db.createConnection();
launch(args);
}
或者调用其他类的main
方法。
如果不需要args
public static void main(String[] args) {
databaseConnection.main(null);
launch(args);
}
如果需要args
public static void main(String[] args) {
databaseConnection.main(args);
launch(args);
}
<强>更新强>
James_D在评论中指出:
在某些情况下,您可能希望使用“纯JavaFX启动”启动应用程序,这将完全绕过main()方法
在这种情况下,移动此
会更好databaseConnection db = new databaseConnection ();
db.createConnection();
到start()
方法。
public void start(Stage stage) throws Exception {
databaseConnection db = new databaseConnection ();
db.createConnection();
Parent root = FXMLLoader.load(getClass().getResource("Frame.fxml"));
Scene scene = new Scene(root);
stage.setTitle("Albert Heijn Handterminal");
stage.setScene(scene);
stage.show();
}