Я создаю приложение Java, которое позволяет пользователям вставлять данные в базу данных MySQL через интерфейс GUI. Он структурирован с использованием основного класса для всех GUI, а затем отдельных классов снаружи для каждой функции (Создание таблиц, Вставка данных и т. Д. c).
Я создал функцию в GUI секция, которая проверяет, когда пользователь нажимает JButton с помощью actionListener, затем открывает JOptionPane, в котором есть панель с некоторыми JTextfields, она переходит в оператор if / else, чтобы проверить, есть ли в первом JTextField текст (остальные данных может быть нулевым). По завершении этого процесса он запускает getText в JTextField и сохраняет его в виде строки.
Основной класс:
package catalogue;
addSupplier.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae) {
//Call a JOptionPane and give it an int value to be able to check status of button presses without another ActionListner
int result = JOptionPane.showConfirmDialog(null, addSupplierPanel, "Please enter supplier name", JOptionPane.OK_CANCEL_OPTION);
//Checks if OK button is pressed
if (result == JOptionPane.OK_OPTION){
//Check if user entered any text into suppNameIn (Cannot be null)
if(suppNameIn.getText().equals("")){
//Dispense error as suppNameIn is empty
System.out.println("Pressed Okay, nothing entered");
} else {
//Grab the text from the JTextField and convert it into a usable string
String suppNameInsert = suppNameIn.getText();
String suppCollectionInsert = suppCollectionIn.getText();
//Confirmation that data has been read in from JTextField correctly
System.out.println(suppNameInsert + " Successfully entered");
System.out.println(suppCollectionInsert + " Successfully entered");
try{
//Connect to DB
Connection conn = CatalogueDB.getConnection();
//Prepare statement to run the insert script using the strings as input variables
PreparedStatement posted = conn.prepareStatement("INSERT INTO supplier (suppName, suppCollection) VALUES ('"+suppNameInsert+"', '"+suppCollectionInsert+"')");
//Push the PreparedStatement 'posted'
posted.executeUpdate();
//Catch if anything goes wrong while connecting to the database
} catch(Exception e){System.out.println("Error adding supplier");}
//Finish by printing a message to say the insert has worked.
finally{
System.out.println("Insert Completed.");
}
}
}
}
});
}
Отдельный класс insertData:
package catalogue;
import java.sql.Connection;
import java.sql.PreparedStatement;
public class insertData {
CatalogueUI.suppNameInsert;
public void insertSupplier() throws Exception{
try{
//Connect to DB
Connection conn = CatalogueDB.getConnection();
PreparedStatement posted = conn.prepareStatement("INSERT INTO supplier (suppName, suppCollection) VALUES ('"+suppNameInsert+"', '"+suppCollectionInsert+"')");
posted.executeUpdate();
} catch(Exception e){System.out.println("Error adding supplier");}
finally{
System.out.println("Insert Completed.");
}
}
}
У меня проблема в том, что я не могу получить доступ к строке вне основного класса. Я неправильно строю это для того, чего хочу достичь, или у меня отдельная проблема, чем я думаю?