отображение полученной информации в других окнах JavaFX
У меня есть код для контроллера поиска туров, где клиент выбирает тур и проверяется есть ли такой в базе данных. Если он есть, то информация о первом попавшемся туре отображается в следующем окне. Мне необходимо, чтобы эта же информация отображалась и в другом окне(контроллер аккаунта), которое открывается через несколько через 3 других.
public class TourSearchController {
@FXML
private TextField departureCityField;
@FXML
private TextField destinationCityField;
@FXML
private DatePicker departureDateField;
@FXML
private DatePicker returnDateField;
@FXML
private TextField adultCountField;
@FXML
private TextField childCountField;
@FXML
private RadioButton hotel5Stars;
@FXML
private RadioButton hotel4Stars;
@FXML
private RadioButton hotel3Stars;
@FXML
private RadioButton hotel2Stars;
@FXML
private RadioButton allInclusive;
@FXML
private RadioButton breakfastOnly;
@FXML
private RadioButton breakfastDinner;
@FXML
private RadioButton halfBoard;
@FXML
private CheckBox waterSlides;
@FXML
private CheckBox swimmingPool;
@FXML
private CheckBox restraunt;
@FXML
private CheckBox spaCenter;
@FXML
private CheckBox gym;
@FXML
private CheckBox childrenWaterSlides;
@FXML
private CheckBox childrenPlayground;
@FXML
private CheckBox childrenMenu;
@FXML
private CheckBox childrenBed;
@FXML
private RadioButton sandBeach;
@FXML
private RadioButton gravelBeach;
@FXML
private Button searchButton;
@FXML
private void handleSearchButtonAction() throws SQLException {
String departureCity = departureCityField.getText();
String city = destinationCityField.getText();
LocalDate departureDate = departureDateField.getValue();
LocalDate returnDate = returnDateField.getValue();
int adults = Integer.parseInt(adultCountField.getText());
int children = Integer.parseInt(childCountField.getText());
long nights = ChronoUnit.DAYS.between(departureDate, returnDate);
String beach = sandBeach.isSelected() ? "песчаный" : "галечный";
String hotelCategory = null;
if (hotel5Stars.isSelected()) {
hotelCategory = "Пятизвездочный";
} else if (hotel4Stars.isSelected()) {
hotelCategory = "Четырехзвездочный";
} else if (hotel3Stars.isSelected()) {
hotelCategory = "Трехзвездочный";
} else if (hotel2Stars.isSelected()) {
hotelCategory = "Двухзвездочный";
}
String mealPlan = null;
if (allInclusive.isSelected()) {
mealPlan = "все включено";
} else if (breakfastOnly.isSelected()) {
mealPlan = "только завтрак";
} else if (breakfastDinner.isSelected()) {
mealPlan = "завтрак и ужин";
} else if (halfBoard.isSelected()) {
mealPlan = "полный пансион";
}
boolean territoryWaterSlides = waterSlides.isSelected();
boolean territorySwimmingPool = swimmingPool.isSelected();
boolean territorySpaCenter = spaCenter.isSelected();
boolean territoryGym = gym.isSelected();
boolean territoryRestraunt = restraunt.isSelected();
boolean childWaterSlides = childrenWaterSlides.isSelected();
boolean childPlayground = childrenPlayground.isSelected();
boolean childMenu = childrenMenu.isSelected();
boolean childBed = childrenBed.isSelected();
searchTour(departureCity, city, (int) nights, adults, children, beach, hotelCategory, mealPlan, territoryWaterSlides, territorySwimmingPool, territorySpaCenter, territoryGym, territoryRestraunt, childMenu, childBed, childPlayground, childWaterSlides);
}
public void searchTour(String departureCity, String city, int nights, int adults, int children, String
beach, String hotelCategory, String mealPlan, boolean waterSlides, boolean swimmingPool, boolean spa, boolean gym,
boolean restaurant, boolean childMenu, boolean childBed, boolean childPlayground, boolean childWaterSlides) {
// Код для поиска туров
try {
DB touragency = new DB();
String query = "SELECT * FROM tours " +
"JOIN hotels ON tours.hotel_id = hotels.hotel_id " +
"JOIN services ON hotels.hotel_id = services.hotel_id " +
"WHERE tours.departure_city = ? " +
"AND tours.city = ? " +
"AND tours.nights = ? " +
"AND tours.adults = ? " +
"AND tours.children = ? " +
"AND hotels.beach = ? " +
"AND hotels.meal_plan = ? " +
"AND hotels.category = ? " +
"AND services.water_slides = ? " +
"AND services.swimming_pool = ? " +
"AND services.spa = ? " +
"AND services.gym = ? " +
"AND services.restaurant = ? " +
"AND services.children_menu = ? " +
"AND services.children_bed = ? " +
"AND services.children_playground = ? " +
"AND services.children_waterslides = ? ";
PreparedStatement statement = touragency.getConnection().prepareStatement(query);
statement.setString(1, departureCity);
statement.setString(2, city);
statement.setInt(3, nights);
statement.setInt(4, adults);
statement.setInt(5, children);
statement.setString(6, beach);
statement.setString(7, mealPlan);
statement.setString(8, hotelCategory);
statement.setBoolean(9, waterSlides);
statement.setBoolean(10, swimmingPool);
statement.setBoolean(11, spa);
statement.setBoolean(12, gym);
statement.setBoolean(13, restaurant);
statement.setBoolean(14, childMenu);
statement.setBoolean(15, childBed);
statement.setBoolean(16, childPlayground);
statement.setBoolean(17, childWaterSlides);
ResultSet resultSet = statement.executeQuery();
Tour foundTour = null; // Создаем переменную для хранения найденного тура
Hotel foundHotel = new Hotel();
Services foundServices = new Services();
foundHotel.setHotelCategory(hotelCategory);
foundHotel.setMealPlan(mealPlan);
foundHotel.setBeach(beach);
foundServices.setChildrenBed(childBed);
foundServices.setChildrenMenu(childMenu);
foundServices.setChildrenPlayground(childPlayground);
foundServices.setChildrenWaterslides(childWaterSlides);
foundServices.setGym(gym);
foundServices.setRestraunt(restaurant);
foundServices.setSpa(spa);
foundServices.setSwimmingPool(swimmingPool);
foundServices.setWaterSlides(waterSlides);
while (resultSet.next()) {
Tour tour = new Tour();
Hotel hotel = new Hotel();
Services services = new Services();
tour.setCountry(resultSet.getString("country"));
tour.setCity(resultSet.getString("city"));
tour.setDepartureCity(resultSet.getString("departure_city"));
tour.setNights(resultSet.getInt("nights"));
tour.setAdults(resultSet.getInt("adults"));
tour.setChildren(resultSet.getInt("children"));
tour.setAirline(resultSet.getString("airline"));
tour.setCost(resultSet.getInt("cost"));
tour.setRoomType(resultSet.getString("room_type"));
hotel.setHotelCategory(resultSet.getString("category"));
hotel.setMealPlan(resultSet.getString("meal_plan"));
hotel.setBeach(resultSet.getString("beach"));
hotel.setHotelName(resultSet.getString("name"));
services.setChildrenBed(resultSet.getBoolean("children_bed"));
services.setChildrenMenu(resultSet.getBoolean("children_menu"));
services.setChildrenPlayground(resultSet.getBoolean("children_playground"));
services.setChildrenWaterslides(resultSet.getBoolean("children_waterslides"));
services.setGym(resultSet.getBoolean("gym"));
services.setRestraunt(resultSet.getBoolean("restaurant"));
services.setSpa(resultSet.getBoolean("spa"));
services.setSwimmingPool(resultSet.getBoolean("swimming_pool"));
services.setWaterSlides(resultSet.getBoolean("water_slides"));
foundTour = tour;
foundHotel = hotel;
foundServices = services;
break;
}
if (foundTour != null) {
// Отображение информации о туре, если тур найден
showTourInfo(foundTour, foundHotel, foundServices);
} else {
// Если тур не найден, выводим сообщение
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("Уведомление");
alert.setHeaderText(null);
alert.setContentText("Нет туров, соответствующих вашим критериям.");
alert.showAndWait();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
private void showTourInfo(Tour foundTour, Hotel foundHotel, Services foundServices) {
try {
FXMLLoader loader = new FXMLLoader(getClass().getResource("/travelagency/fxml/TourInfo.fxml"));
Parent root = loader.load();
TourInfoController controller = loader.getController();
controller.initData(foundTour, foundHotel, foundServices);
// Получение экземпляра контроллера AccountController из FXMLLoader
FXMLLoader accountLoader = new FXMLLoader(getClass().getResource("/travelagency/fxml/Account.fxml"));
Parent accountRoot = accountLoader.load();
AccountController accountController = accountLoader.getController();
// Передача данных в контроллер AccountController
accountController.updateData(foundTour, foundHotel, foundServices);
Stage stage = new Stage();
stage.setScene(new Scene(root));
// stage.setScene(new Scene(accountRoot));
stage.show();
Stage currentStage = (Stage) searchButton.getScene().getWindow();
currentStage.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
код контроллера аккаунта
package travelagency.controllers;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.stage.Stage;
import travelagency.Hotel;
import travelagency.Services;
import travelagency.Tour;
import java.io.IOException;
import java.time.LocalDate;
public class AccountController {
@FXML
private Label adultsLabel;
@FXML
private Label airlinesLabel;
@FXML
private Button backButton;
@FXML
private Label beachLabel;
@FXML
private Label birthDateLabel;
@FXML
private Label childrenBedLabel;
@FXML
private Label childrenLabel;
@FXML
private Label childrenMenuLabel;
@FXML
private Label childrenPlaygroundLabel;
@FXML
private Label childrenWaterSlidesLabel;
@FXML
private Label cityLabel;
@FXML
private Label countryLabel;
@FXML
private Label departureCityLabel;
@FXML
private Label departureDateLabel;
@FXML
private Label destinationCityLabel;
@FXML
private Label fullNameLabel;
@FXML
private Label gymLabel;
@FXML
private Label hotelCategoryLabel;
@FXML
private Label hotelNameLabel;
@FXML
private Label mealPlanLabel;
@FXML
private Label phoneNumberLabel;
@FXML
private Label restrauntLabel;
@FXML
private Label returnAirlinesLabel;
@FXML
private Label returnCityLabel;
@FXML
private Label returnDateLabel;
@FXML
private Label returnDepartureCityLabel;
@FXML
private Label roomTypeLabel;
@FXML
private Label spaCenterLabel;
@FXML
private Label swimmingPoolLabel;
@FXML
private Label waterSlidesLabel;
@FXML
void backButtonClicked(ActionEvent event) throws IOException {
try {
FXMLLoader loader = new FXMLLoader(getClass().getResource("/travelagency/fxml/Main.fxml"));
Parent root = loader.load();
MainWinController controller = loader.getController();
// controller.initData(login, password, isClient, isManager); // передача данных, если необходимо
Stage stage = new Stage();
stage.setScene(new Scene(root));
stage.show();
// Закрытие текущего окна
Stage currentStage = (Stage) backButton.getScene().getWindow();
currentStage.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
public void updateData(Tour foundTour, Hotel foundHotel, Services foundServices) {
countryLabel.setText(foundTour.getCountry());
destinationCityLabel.setText(foundTour.getCity());
departureCityLabel.setText(foundTour.getDepartureCity());
adultsLabel.setText(String.valueOf(foundTour.getAdults()));
childrenLabel.setText(String.valueOf(foundTour.getChildren()));
roomTypeLabel.setText(foundTour.getRoomType());
cityLabel.setText(foundTour.getCity());
departureCityLabel.setText(foundTour.getDepartureCity());
returnCityLabel.setText(foundTour.getCity());
returnDepartureCityLabel.setText(foundTour.getDepartureCity());
airlinesLabel.setText(foundTour.getAirline());
returnAirlinesLabel.setText(foundTour.getAirline());
returnAirlinesLabel.setText(foundTour.getAirline());
hotelCategoryLabel.setText(foundHotel.getHotelCategory());
hotelNameLabel.setText(foundHotel.getHotelName());
mealPlanLabel.setText(foundHotel.getMealPlan());
beachLabel.setText(foundHotel.getBeach());
waterSlidesLabel.setText(foundServices.isWaterSlides() ? "Водные горки" : "");
swimmingPoolLabel.setText(foundServices.isSwimmingPool() ? "Бассейн" : "");
spaCenterLabel.setText(foundServices.isSpa() ? "СПА" : "");
gymLabel.setText(foundServices.isGym() ? "Спортзал" : "");
restrauntLabel.setText(foundServices.isRestraunt() ? "Ресторан" : "");
childrenBedLabel.setText(foundServices.isChildrenBed() ? "Детская кровать" : "");
childrenMenuLabel.setText(foundServices.isChildrenMenu() ? "Десткое меню" : "");
childrenPlaygroundLabel.setText(foundServices.isChildrenPlayground() ? "Площадка для детей" : "");
childrenWaterSlidesLabel.setText(foundServices.isChildrenWaterslides() ? "Водные горки для детей" : "");
System.out.println("Received Tour: " + foundTour.getRoomType());
System.out.println("Received Hotel: " + foundHotel.getHotelName() + foundHotel.getHotelCategory());
System.out.println("Received Services: " + foundServices.isChildrenWaterslides() + foundServices.isGym());
// Отладочный вывод для проверки заполненности объектов
if (foundTour != null) {
System.out.println("Tour data is not null");
} else {
System.out.println();
}
}
}