I want to implement a program where there is:
- A MySQLConnection class that handles the database connection
- A Screen class for the GUI that takes input to be stored in the DB
- Main class
I want to call the MySQLConnection object created in the main method from the Screen class.
What I have attempted so far - erroneously- is as follows. Pointers to resolve this problem are greatly appreciated.
Thanks in advance!
Main Class:
public class Main {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
//Start main screen
Screen start = new Screen();
start.setVisible(true);
//create db connection
**MySQLConnection sqlConn = new MySQLConnection();
Connection con=sqlConn.connectToDatabase();**
} catch (Exception e) {
e.printStackTrace();
}
}
});
MySQL Connection class:
public class MySQLConnection {
public Connection connectToDatabase() {//connect to db }
public void addToDatabase(String tableName, ArrayList<String> columns, ArrayList<String> values) {//add a row to table in db}
public void closeConnection() {//close db connection}
}
AddScreen class:
public class Screen extends JFrame{
ArrayList<String> mainValues= new ArrayList<String>();
//Create GUI
public Screen(){
...
ArrayList<String> mainValues= new ArrayList<String>();
String mainId = mainI.getText();
String mainName = mainN.getText();
mainValues.add(mainId);
mainValues.add(mainName);
}
public void saveToDatabase() {
String[] mainColumns= {"mid", "mname"};
**con.addToDatabase("main_category", mainColumns, mainValues);**
}
}