JavaFx Разделение проекта на компоненты

398
27 сентября 2017, 09:10

Есть проект. Закидывает вводимые данные в таблицу. Как разделить этот проект на подклассы? То есть, отделить на 3 fxml файла. Главный,отдельно таблица и отдельно текстовое поле с кнопкой. И каждому fxml файлу контроллер.

public class Main extends Application {
    @Override
    public void start(Stage primaryStage) throws Exception{
        Parent root = FXMLLoader.load(getClass().getResource("tables.fxml"));
        primaryStage.setTitle("Hello World");
        primaryStage.setScene(new Scene(root, 600, 400));
        primaryStage.show();
    }
    public static void main(String[] args) {
        launch(args);
    }
 }
public class Controller implements Initializable {
    public TableView<InputObject> tableInfo;
    public TextArea inputArea;
    public Button inputButton;
    public TableColumn<InputObject, String> col1;
    @Override
    public void initialize(URL location, ResourceBundle resources) {
        col1.setCellValueFactory(new PropertyValueFactory<>("text"));
    }
    public void inputToTable() {
        if(inputArea.getText() != "") {
            tableInfo.getItems().addAll(new InputObject(inputArea.getText()));
            inputArea.clear();
        }
    }
}
public class InputObject {
    String text;
    public InputObject(String text) {
        this.text = text;
    }
    public String getText() {
        return text;
    }
    public void setText(String text) {
        this.text = text;
    }
}

и

<BorderPane fx:controller="sample.Controller" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8.0.111" xmlns:fx="http://javafx.com/fxml/1">
   <left>
      <TableView fx:id="tableInfo" prefHeight="400.0" prefWidth="330.0" BorderPane.alignment="CENTER">
        <columns>
          <TableColumn fx:id="col1" prefWidth="75.0" text="Output" />
        </columns>
         <columnResizePolicy>
            <TableView fx:constant="CONSTRAINED_RESIZE_POLICY" />
         </columnResizePolicy>
      </TableView>
   </left>
   <center>
      <VBox alignment="TOP_CENTER" prefHeight="200.0" prefWidth="100.0" BorderPane.alignment="CENTER">
         <children>
            <TextArea fx:id="inputArea" prefHeight="188.0" prefWidth="270.0" />
            <Button fx:id="inputButton" onAction="#inputToTable" mnemonicParsing="false" text="Input">
               <VBox.margin>
                  <Insets bottom="30.0" left="30.0" right="30.0" top="30.0" />
               </VBox.margin>
            </Button>
         </children>
      </VBox>
   </center>
</BorderPane>
Answer 1
public class Main extends Application {
    private RootController rootController;
    private TableController tableController;
    private TextController textController;
    @Override
    public void start(Stage primaryStage) throws Exception{
        FXMLLoader loader;
        loader = new FXMLLoader( getClass().getClassLoader().getResource("./root.fxml"));
        loader.setController( rootController = new RootController() );
        BorderPane root = (BorderPane)loader.load();
        loader = new FXMLLoader( getClass().getClassLoader().getResource("./table.fxml"));
        loader.setController( tableController = new TableController() );
        root.setLeft( loader.load() );
        loader = new FXMLLoader( getClass().getClassLoader().getResource("./text.fxml"));
        loader.setController( textController = new TextController( tableController.getTable() ) );
        root.setRight( loader.load() );
        primaryStage.setTitle("Hello World");
        primaryStage.setScene(new Scene(root, 600, 400));
        primaryStage.show();
    }
    public static void main(String[] args) {
        launch(args);
    }
}
class RootController{
    @FXML
    private void initialize() {}
}
class TableController{
    @FXML private TableView<InputObject> tableInfo;
    @FXML public TableColumn<InputObject, String> col1;
    @FXML
    private void initialize() {
        col1.setCellValueFactory(new PropertyValueFactory<>("text"));
    }
    public TableView getTable() {
        return tableInfo;
    }
}
class TextController{
    private final TableView tableInfo;
    public TextController( TableView tableInfo ) {
        this.tableInfo = tableInfo;
    }
    @FXML public TextArea inputArea;
    @FXML public Button inputButton;
    @FXML
    private void initialize() {
    }
    @FXML
    public void inputToTable() {
//        нельзя так сравнивать строки
//        if(inputArea.getText() != "") {
        if( !inputArea.getText().equals( "" ) ) { // или !inputArea.getText().isEmpty()
            tableInfo.getItems().addAll(new InputObject(inputArea.getText()));
            inputArea.clear();
        }
    }
}
<!--root.fxml-->
<BorderPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8.0.111" xmlns:fx="http://javafx.com/fxml/1"/>
<!--table.fxml-->
<TableView fx:id="tableInfo" prefHeight="400.0" prefWidth="330.0" BorderPane.alignment="CENTER" xmlns="http://javafx.com/javafx/8.0.111" xmlns:fx="http://javafx.com/fxml/1">
  <columns>
    <TableColumn fx:id="col1" prefWidth="75.0" text="Output" />
  </columns>
   <columnResizePolicy>
      <TableView fx:constant="CONSTRAINED_RESIZE_POLICY" />
   </columnResizePolicy>
</TableView>
<!--text.fxml-->
<VBox alignment="TOP_CENTER" BorderPane.alignment="CENTER" xmlns="http://javafx.com/javafx/8.0.111" xmlns:fx="http://javafx.com/fxml/1">
   <children>
      <TextArea fx:id="inputArea" prefHeight="188.0" prefWidth="270.0" />
      <Button fx:id="inputButton" onAction="#inputToTable" mnemonicParsing="false" text="Input">
         <VBox.margin>
            <Insets bottom="30.0" left="30.0" right="30.0" top="30.0" />
         </VBox.margin>
      </Button>
   </children>
</VBox>
READ ALSO
Помогите с авторизацией Google Oauth2

Помогите с авторизацией Google Oauth2

Есть метод авторизации через VK API, после него запускается RecyclerView!! Щас хочу сделать авторизацию через GOOGLE Oauth2, что бы когда токен одобрен, то сразу...

223
Рандомное значение из массива String

Рандомное значение из массива String

Передо мной стоит задача: написать класс "Студенты" в котором они будут выбирать себе старостуНо для начала я бы хотела наделить студентов...

367
VirtualBox API Exception

VirtualBox API Exception

Доброе время сутокЗадача следующая, поднять, используя API Java, виртуальную машину и запустить на ней любую элементарную программу

187
NullPointerException at LoadedApk.getAssets

NullPointerException at LoadedApk.getAssets

Через Developer Console получил известие о такой ошибкеС чем она может быть связана? Не дубликат вопроса о NullPointerException в общем смысле

282