Вы в основном должны следовать инструкциям @Slaw.Создайте Model
.Разделите Model
между двумя Controllers
.Соблюдайте текущую модель Customer
и реагируйте соответственно.MCVE Ниже:
Основной класс: (загрузите обе ступени с правильной сценой. Создайте модель и передайте ее обоим контроллерам):
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
/**
*
* @author sedri
*/
public class JavaFXApplication36 extends Application {
@Override
public void start(Stage stage) {
try {
FXMLLoader listViewFXMLLoader = new FXMLLoader(getClass().getResource("ListViewFXML.fxml"));
Parent listViewRoot = listViewFXMLLoader.load();
ListViewController listViewController = listViewFXMLLoader.getController();
Scene scene1 = new Scene(listViewRoot);
stage.setScene(scene1);
FXMLLoader detailsFXMLLoader = new FXMLLoader(getClass().getResource("DetailsFXML.fxml"));
Parent detailsRoot = detailsFXMLLoader.load();
DetailsController detailsController = detailsFXMLLoader.getController();
Scene scene2 = new Scene(detailsRoot);
Stage stage2 = new Stage();
stage2.setScene(scene2);
DataModel model = new DataModel();
listViewController.initModel(model);
detailsController.initModel(model);
stage.show();
stage2.show();
} catch (IOException ex) {
Logger.getLogger(JavaFXApplication36.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
Класс модели: (в ногу с текущим клиентом и списком наблюдаемых клиентов)
import javafx.beans.Observable;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
/**
*
* @author sedrick
*/
public class DataModel {
private final ObservableList<Customer> customerList = FXCollections.observableArrayList(customer -> new Observable[]{customer.nameProperty(), customer.ageProperty()});
private final ObjectProperty<Customer> currentCustomer = new SimpleObjectProperty();
public ObjectProperty<Customer> currentCustomerProperty() {
return currentCustomer;
}
public void setCurrentCustomer(Customer currentCustomer) {
this.currentCustomer.set(currentCustomer);
}
public Customer getCurrentCustomer() {
return this.currentCustomer.get();
}
public ObservableList<Customer> loadCustomers()
{
customerList.add(new Customer("John Doe", 21));
customerList.add(new Customer("Jane Joe", 20));
return customerList;
}
}
Класс клиента:
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
/**
*
* @author sedrick
*/
public class Customer {
private final StringProperty name = new SimpleStringProperty();
private final IntegerProperty age = new SimpleIntegerProperty();
public Customer(String name, int age) {
this.name.set(name);
this.age.set(age);
}
public String getName()
{
return this.name.get();
}
public void setName(String name)
{
this.name.set(name);
}
public StringProperty nameProperty()
{
return this.name;
}
public int getAge()
{
return this.age.get();
}
public void setAge(int age)
{
this.age.set(age);
}
public IntegerProperty ageProperty()
{
return this.age;
}
}
Контроллер ListView: (инициализация модели, настройка ListView и наблюдение за текущими свойствами клиента)
import java.net.URL;
import java.util.ResourceBundle;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
/**
*
* @author sedri
*/
public class ListViewController implements Initializable {
@FXML private ListView<Customer> listView;
private DataModel model;
@Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
}
public void initModel(DataModel model)
{
// ensure model is only set once:
if (this.model != null) {
throw new IllegalStateException("Model can only be initialized once");
}
listView.getSelectionModel().selectedItemProperty().addListener((obs, oldCustomer, newCustomer) ->
model.setCurrentCustomer(newCustomer));
model.currentCustomerProperty().addListener((obs, oldCustomer, newCustomer) -> {
if (newCustomer == null) {
listView.getSelectionModel().clearSelection();
} else {
listView.getSelectionModel().select(newCustomer);
}
});
listView.setCellFactory(lv -> new ListCell<Customer>() {
@Override
public void updateItem(Customer customer, boolean empty) {
super.updateItem(customer, empty);
if (empty) {
setText(null);
} else {
setText("Name: " + customer.getName() + " Age: " + customer.getAge());
}
}
});
listView.setItems(model.loadCustomers());
}
}
ListView FXML:
<StackPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8.0.171" xmlns:fx="http://javafx.com/fxml/1" fx:controller="javafxapplication36.ListViewController">
<children>
<ListView fx:id="listView" prefHeight="200.0" prefWidth="200.0" />
</children>
</StackPane>
DetailsController: (Инициализация модели и наблюдение за текущими свойствами клиента)
import java.net.URL;
import java.util.ResourceBundle;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TextField;
/**
* FXML Controller class
*
* @author sedri
*/
public class DetailsController implements Initializable {
@FXML TextField tfName, tfAge;
private DataModel model;
/**
* Initializes the controller class.
*/
@Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
}
public void initModel(DataModel model) {
// ensure model is only set once:
if (this.model != null) {
throw new IllegalStateException("Model can only be initialized once");
}
this.model = model ;
model.currentCustomerProperty().addListener((observable, oldCustomer, newCustomer) -> {
if(newCustomer == null){
tfName.setText("");
tfAge.setText("");
}
else{
tfName.setText(newCustomer.getName());
tfAge.setText(Integer.toString(newCustomer.getAge()));
}
});
}
}
Подробности FXML:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.geometry.Insets?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.VBox?>
<VBox alignment="CENTER" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8.0.171" xmlns:fx="http://javafx.com/fxml/1" fx:controller="javafxapplication36.DetailsController">
<children>
<Label text="Name" />
<TextField fx:id="tfName" />
<Label text="Age" />
<TextField fx:id="tfAge" />
</children>
<padding>
<Insets left="20.0" right="20.0" />
</padding>
</VBox>
Дополнительная информация:
@ James D ответ на Model-View-Controller (MVC) .
Код GitHub .