Порядок элементов в Anchor Pane - PullRequest
0 голосов
/ 19 ноября 2018

, когда я пытаюсь инициализировать Anchor Pane, происходят странные вещи: если я помещаю элементы в таком порядке, я не могу щелкнуть мышью, например, по элементам списка.

AnchorPane root = new AnchorPane(listLoader.load(), fieldLoader.load(), textareaLoader.load(), buttonLoader.load(),  menuLoader.load());

Но если я напишу это таким образом, я смогу выбрать элементы в списке, но не элементы в строке меню:

AnchorPane root = new AnchorPane(fieldLoader.load(), textareaLoader.load(), buttonLoader.load(),  menuLoader.load(), listLoader.load());

Знаете ли вы, как мне написать элементы, чтобы сделать хотя бы кнопку, меню и список интерактивными?

Это полный код:

@Override
public void start(Stage stage) throws Exception {
    FXMLLoader listLoader = new FXMLLoader(getClass().getResource("lista.fxml"));
    FXMLLoader textareaLoader = new FXMLLoader(getClass().getResource("textarea.fxml"));
    FXMLLoader fieldLoader = new FXMLLoader(getClass().getResource("textfield.fxml"));
    FXMLLoader menuLoader = new FXMLLoader(getClass().getResource("menubar.fxml"));
    FXMLLoader buttonLoader = new FXMLLoader(getClass().getResource("button.fxml"));

    AnchorPane root = new AnchorPane(listLoader.load(), fieldLoader.load(), textareaLoader.load(), buttonLoader.load(),  menuLoader.load());

    ListController listController = listLoader.getController();
    TextAreaController textareaController = textareaLoader.getController();
    TextFieldController fieldController = fieldLoader.getController();
    MenuBarController menuController = menuLoader.getController();
    ButtonController buttonController = buttonLoader.getController();

    DataModel model = new DataModel();
    listController.initModel(model);
    textareaController.initModel(model);
    fieldController.initModel(model);
    menuController.initModel(model);
    buttonController.initModel(model);

    Scene scene = new Scene(root, 603, 403);
    stage.setScene(scene);
    stage.show();
}

Lista.fxml:

<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="mailbox.ListController">

Button.fxml:

<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="mailbox.ButtonController">

MenuBar.fxml:

<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/8" fx:controller="mailbox.MenuBarController">
<children>
    <MenuBar fx:id="menuBar" layoutX="0.0" layoutY="0.0">
        <menus>
            <Menu text="File">
                <items>
                    <MenuItem onAction="#elimina" text="Elimina" />
                </items>
            </Menu>
            <Menu text="Cambia Account">
                <items>
                    <MenuItem fx:id="email1" text="filippo@hotmail.it" />
                    <MenuItem fx:id="email2" text="giancarlo@yahoo.it" />
                    <MenuItem fx:id="email3" text="alessandro@gmail.it" />
                </items>
            </Menu>
        </menus>
    </MenuBar>
</children>

Textarea.fxml:

<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/8" fx:controller="mailbox.TextAreaController">

Textfield.fxml:

<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" mouseTransparent="false" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="mailbox.TextFieldController">

EDIT: Так я должен объявить более одной Anchor Pane и прикрепить их к основной Anchor Pane?

    AnchorPane root = new AnchorPane();

    AnchorPane lista = new AnchorPane(listLoader.load());
    AnchorPane textarea = new AnchorPane(textareaLoader.load());
    AnchorPane field = new AnchorPane(fieldLoader.load());
    AnchorPane menu = new AnchorPane(menuLoader.load());
    AnchorPane button = new AnchorPane(buttonLoader.load());

    root.getChildren().addAll(lista, textarea, field, menu, button);

EDIT2: это вывод моей программы, могу ли я создать ее с BorderPane? Поскольку он автоматически привязывает элементы справа, слева и т.д., и, например, я не могу поместить текстовое поле, как вы можете видеть на изображении Output

1 Ответ

0 голосов
/ 19 ноября 2018

Возможно, последовательно загруженные панели имеют одинаковые размеры. После загрузки их вы получаете стек с одинаковыми размерами. В этом случае только самая верхняя панель (добавленная как последняя) реагирует на события мыши. Я бы посоветовал предоставить правильные размеры и анкеры для каждой панели. Если мой тезис неверен, пожалуйста, предоставьте больше кода.

РЕДАКТИРОВАТЬ: если child1 и child2 имеют одинаковые размеры, будет виден только синий, но все же будет красный, но снизу и весь синий. Та же ситуация с вашим приложением. Кстати, вы неправильно используете AnchorPane. AnchorPane предназначен для привязки дочерних элементов.

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;

public class AnchorPaneTest extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage stage) throws Exception {
        AnchorPane anchorPane = new AnchorPane();

        AnchorPane child1 = new AnchorPane();
        child1.setPrefSize(400., 600.);
        child1.setStyle("-fx-background-color: red;");

        AnchorPane child2 = new AnchorPane();
        child2.setPrefSize(400., 300.);
        child2.setStyle("-fx-background-color: blue;");

        anchorPane.getChildren().addAll(child1, child2);

        stage.setScene(new Scene(anchorPane));
        stage.show();
    }
}
...