Я пытаюсь получить значение, которое находится внутри табличного JavaFx GUI.Данные из моей базы данных, и мне нужно извлечь эти данные в виде строки, чтобы отправить их в метод и обновить базу данных.
Вот код, который у меня есть для tableView, подключенного к графическому интерфейсу. У меня проблемы с получением значения String.
public class YourFlights {
static Stage window;
static TableView table;
static TextField nameInput;
static TextField arrInput;
static TextField depInput;
private ReservationDataAccessor dataAccessor;
Stage primaryStage = new Stage();
int userId = MainPage.userId;
public void start(Stage primaryStage) throws SQLException, ClassNotFoundException {
dataAccessor = new ReservationDataAccessor("com.mysql.cj.jdbc.Driver", "jdbc:mysql://localhost:3306/demo", "flightuser",
"flightuser");
window = primaryStage;
window.setTitle("Your Flights");
// Flight column
TableColumn<Flight, String> flightIDColumn = new TableColumn<>("flight ID");
flightIDColumn.setCellValueFactory(new PropertyValueFactory<>("flightNumber"));
flightIDColumn.setMinWidth(200);
// Arrival_Date Column
TableColumn<Flight, String> departingCityColumn = new TableColumn<>("Departing City");
departingCityColumn.setCellValueFactory(new PropertyValueFactory<>("departureCity"));
departingCityColumn.setMinWidth(200);
// Departure_Date Column
TableColumn<Flight, String> arrivalCityColumn = new TableColumn<>("Arrival City");
arrivalCityColumn.setCellValueFactory(new PropertyValueFactory<>("arrivalCity"));
arrivalCityColumn.setMinWidth(200);
// Departure City Column
TableColumn<Flight, String> departureTimeColumn = new TableColumn<>("Departure Time");
departureTimeColumn.setCellValueFactory(new PropertyValueFactory<>("timeOfDeparture"));
departureTimeColumn.setMinWidth(200);
// Arrival_Date Column
TableColumn<Flight, String> arrivalTimeColumn = new TableColumn<>("Arrival Time");
arrivalTimeColumn.setCellValueFactory(new PropertyValueFactory<>("timeOfArrival"));
arrivalTimeColumn.setMinWidth(200);
// Arrival_Date Column
TableColumn<Flight, String> flightDateColumn = new TableColumn<>("Flight Date");
flightDateColumn.setCellValueFactory(new PropertyValueFactory<>("flightDate"));
flightDateColumn.setMinWidth(200);
//Name input
nameInput = new TextField();
nameInput.setPromptText("Name");
nameInput.setMinWidth(100);
//departure input
arrInput = new TextField();
arrInput.setPromptText("Arr");
//departure input
depInput = new TextField();
depInput.setPromptText("Dep");
//Button
Button addButton = new Button("Add");
//addButton.setOnAction(e -> addButtonClicked());
Button deleteButton = new Button("Delete");
deleteButton.setOnAction(e -> deleteButtonClicked());
Button btn = new Button("Go Back");
HBox hBox = new HBox();
hBox.setPadding(new Insets(10,10,10,10));
hBox.setSpacing(10);
hBox.getChildren().addAll(nameInput, arrInput, depInput, addButton, deleteButton, btn);
btn.setOnAction(e -> {
MainPage m2 = new MainPage();
try {
m2.start(primaryStage);
} catch (Exception e1) {
e1.printStackTrace();
}
});
table = new TableView<>();
table.getColumns().addAll(flightIDColumn, departingCityColumn, arrivalCityColumn, departureTimeColumn,
arrivalTimeColumn, flightDateColumn);
table.setItems(getFlight());
VBox vBox = new VBox();
vBox.getChildren().addAll(table, hBox);
Scene scene = new Scene(vBox);
window.setScene(scene);
window.show();
}
public ObservableList<Flight> getFlight() throws SQLException {
ObservableList<Flight> flights = FXCollections.observableArrayList();
flights.addAll(dataAccessor.getAllReservationList(userId));
return flights;
}
// Delete button clicked
public static void deleteButtonClicked(){
ObservableList<Flight> flightSelected, allFlights;
allFlights = table.getItems();
flightSelected = table.getSelectionModel().getSelectedItems();
flightSelected.forEach(allFlights ::remove);
try {
String listString = table.getSelectionModel().getSelectedItems().toString();
System.out.println(listString);
ReservationDataAccessor.deleteReservation(Integer.parseInt(listString));
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/* //Add button clicked
public static void addButtonClicked(){
Flight flight = new Flight();
flight.setName(nameInput.getText());
flight.setArr(arrInput.getText());
flight.setDep(depInput.getText());
table.getItems().add(flight);
nameInput.clear();
arrInput.clear();
depInput.clear();
}
*/
Это конкретный код, который я использую, чтобы попытаться получить строку из таблицы, затем превратить эту строку в целое число и отправить его в метод.Проблема в том, что String только указывает на адрес и не дает мне значения, которые я хочу, которые в основном являются просто числами внутри Strings.или просто цифры не уверены.
public static void deleteButtonClicked(){
ObservableList<Flight> flightSelected, allFlights;
allFlights = table.getItems();
flightSelected = table.getSelectionModel().getSelectedItems();
flightSelected.forEach(allFlights ::remove);
try {
String listString = table.getSelectionModel().getSelectedItems().toString();
System.out.println(listString);
ReservationDataAccessor.deleteReservation(Integer.parseInt(listString));
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Этот код используется в качестве объекта доступа к данным.Он запускает методы для извлечения и вставки в базу данных.
public class ReservationDataAccessor {
static int userId = MainPage.userId;
private static Connection connection;
private String myQuery = null;
public ReservationDataAccessor(String driverClassName, String dbURL, String user, String password)
throws SQLException, ClassNotFoundException {
Class.forName(driverClassName);
connection = DriverManager.getConnection(dbURL, user, password);
}
public void shutdown() throws SQLException {
if (connection != null) {
connection.close();
}
}
// gets all of user's reservation
public List<Reservation> getAllReservationList(int userId) throws SQLException {
try (Statement stmnt = connection.createStatement();
ResultSet rs = stmnt.executeQuery(
"Select Reservation.FlightId, departingCity, arrivalCity, arrivalTime, departureTime, flightDate from \n"
+ "Reservation inner join Flight on Reservation.Flightid = Flight.FlightId where customerId ="
+ userId);) {
List<Reservation> allReservationsList = new ArrayList<>();
while (rs.next()) {
String flightId = rs.getString("flightId");
String flightDate = rs.getString("flightDate");
String timeOfDeparture = rs.getString("departureTime");
String timeOfArrival = rs.getString("arrivalTime");
String departureCity = rs.getString("departingCity");
String arrivalCity = rs.getString("arrivalCity");
Reservation reservation = new Reservation(flightId, flightDate, timeOfDeparture, timeOfArrival,
departureCity, arrivalCity);
allReservationsList.add(reservation);
}
return allReservationsList;
}
}
// adds reservations
//needs to be modified and tested
public static String addReservation(String flightNumber) throws SQLException {
String query = " INSERT INTO Reservation (FlightID, CustomerId) VALUES (?, ?)";
PreparedStatement preparedStmt = connection.prepareStatement(query);
// preparedStmt.setString(1, reservationId);
preparedStmt.setInt(0, Integer.parseInt(flightNumber));
preparedStmt.setInt(1, userId);
preparedStmt.execute();
connection.close();
// Reservation reservation = new Reservation(flightNumber, userId);
return flightNumber;
}
// delete reservations
//needs to be modified and tested
public static int deleteReservation(int flightId) throws SQLException {
String query = "DELETE Reservation FROM Reservation WHERE FlightID= '?' AND CustomerID= '?'";
PreparedStatement preparedStmt = connection.prepareStatement(query);
preparedStmt.setInt(0, flightId);
preparedStmt.setInt(1, userId);
preparedStmt.execute();
connection.close();
return flightId;
}
}