Форум программистов, компьютерный форум, киберфорум
Java: GUI, графика
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.82/11: Рейтинг темы: голосов - 11, средняя оценка - 4.82
39 / 28 / 8
Регистрация: 14.04.2012
Сообщений: 249

Подгрузить fxml в компонент TabPane

28.05.2016, 12:54. Показов 2522. Ответов 5

Студворк — интернет-сервис помощи студентам
Подскажите как подгрузить fxml в компонент TabPane в первую или вторую вкладку
0
Programming
Эксперт
39485 / 9562 / 3019
Регистрация: 12.04.2006
Сообщений: 41,671
Блог
28.05.2016, 12:54
Ответы с готовыми решениями:

Как подгрузить fxml
Всем привет. Народ подскажите как реализовать данный замысел: Что должно быть: есть главный fxml в нем есть таблица и хочу в ячейку...

Вкладки в TabPane
Имеется программа, в которой пользователь может добавлять сколько захочет вкладок. Имеется панель с несколькими управляющими кнопками...

Скрыть один из Tab-ов в TabPane
Добрый день, использую TabPane. Необходимо скрыть один из табов. Пробовал делать следующим способом: ...

5
636 / 528 / 165
Регистрация: 01.04.2010
Сообщений: 1,843
28.05.2016, 14:19
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
@Override
public void start(final Stage primaryStage) throws Exception {
    final TabPane tabPane = new TabPane();
 
    final BorderPane border = new BorderPane();
    border.setTop(button(tabPane));
    border.setCenter(tabPane);
 
    primaryStage.setScene(new Scene(border));
    primaryStage.setWidth(800);
    primaryStage.setHeight(600);
    primaryStage.show();
}
 
private Button button(final TabPane tabPane) {
    final Button button = new Button("add tab");
    button.setOnAction(e -> {
        final ObservableList<Tab> tabs = tabPane.getTabs();
        final Tab tab = loadTabFromFxml();
        tab.setText("From FXML " + (tabs.size() + 1));
        tabs.add(tab);
    });
    return button;
}
 
private Tab loadTabFromFxml() {
    final FXMLLoader loader = new FXMLLoader();
    try {
        return loader.load(new ByteArrayInputStream(
            "<?import javafx.scene.web.*?><?import javafx.scene.control.*?><Tab><content><HTMLEditor/></content></Tab>".getBytes(UTF_8)
        ));
    } catch (final IOException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}
1
39 / 28 / 8
Регистрация: 14.04.2012
Сообщений: 249
28.05.2016, 20:28  [ТС]
Не до конца понял как подгрузить.
Вот класс root
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
public class mainBackup extends Application {
    private Stage primaryStage;
    private SplitPane rootView;
 
    public static void main(String[] args) {
        launch(args);
    }
 
    @Override
    public void start(Stage primaryStage) {
        this.primaryStage = primaryStage;
 
        initRootView();
    }
 
    // инициализация главного окна
    public void initRootView()
    {
        try {
            // Load root layout from fxml file.
            FXMLLoader loader = new FXMLLoader();
            loader.setLocation(mainBackup.class.getResource("view/rootView.fxml"));
            rootView = (SplitPane) loader.load();
            // Show the scene containing the root layout.
            Scene scene = new Scene(rootView);
            primaryStage.setTitle("Резервное копирование 1.0");
            primaryStage.setMinHeight(400);
            primaryStage.setMinWidth(600);
            primaryStage.setScene(scene);
            showBackup();
 
            primaryStage.show();
        } catch (IOException e)
        {
            e.printStackTrace();
        }
    }
 
    // отобразить  backup.fxml на панели
    public void showBackup() {
        try{
 
            FXMLLoader loader = new FXMLLoader();
            loader.setLocation(mainBackup.class.getResource("view/backup.fxml"));
            AnchorPane backup = (AnchorPane) loader.load();
 
            // Подключение в панель TabPane
            rootView.getItems().
 
 
        } catch(IOException e) {
            e.printStackTrace();
        }
    }
 
}
Далее rootView.fxml

HTML5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
<?xml version="1.0" encoding="UTF-8"?>
 
<?import javafx.scene.layout.*?>
<?import java.lang.*?>
<?import javafx.scene.control.*?>
 
<SplitPane dividerPositions="0.29797979797979796" maxHeight="-Infinity" maxWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1">
  <items>
    <AnchorPane maxWidth="180.0" minWidth="180.0" prefHeight="180.0" prefWidth="180.0">
         <children>
            <Button layoutX="14.0" layoutY="39.0" mnemonicParsing="false" text="+" textAlignment="CENTER" AnchorPane.leftAnchor="10.0" />
            <Label layoutX="41.0" layoutY="14.0" prefHeight="17.0" prefWidth="99.0" text="Список архивов" AnchorPane.leftAnchor="41.0" AnchorPane.rightAnchor="40.0" AnchorPane.topAnchor="10.0" />
            <TextField layoutX="5.0" layoutY="14.0" prefHeight="25.0" prefWidth="134.0" visible="false" AnchorPane.leftAnchor="40.0" AnchorPane.topAnchor="40.0" />
            <Label layoutX="45.0" layoutY="43.0" prefHeight="17.0" prefWidth="122.0" AnchorPane.rightAnchor="10.0" />
         </children></AnchorPane>
    <AnchorPane prefHeight="398.0" prefWidth="417.0">
         <children>
            <TabPane prefHeight="398.0" prefWidth="417.0" tabClosingPolicy="UNAVAILABLE" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
              <tabs>
                <Tab text="Резервное копирование">
                  <content>
                    <AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="180.0" prefWidth="200.0">
                           <children>
                              <Button layoutX="14.0" layoutY="14.0" mnemonicParsing="false" text="Где хранить архив?" AnchorPane.leftAnchor="10.0" AnchorPane.topAnchor="10.0" />
                              <Button layoutX="220.0" layoutY="10.0" mnemonicParsing="false" text="Что хранить в архиве?" AnchorPane.rightAnchor="52.0" AnchorPane.topAnchor="10.0" />
                              <Label layoutX="14.0" layoutY="45.0" prefHeight="17.0" prefWidth="34.0" text="Диск:" AnchorPane.leftAnchor="10.0" />
                              <Label layoutX="97.0" layoutY="45.0" prefHeight="17.0" prefWidth="93.0" text="не выбран" AnchorPane.leftAnchor="97.0" />
                              <ListView layoutX="188.0" layoutY="45.0" prefHeight="272.0" prefWidth="210.0" AnchorPane.bottomAnchor="52.0" AnchorPane.leftAnchor="188.0" AnchorPane.rightAnchor="14.0" AnchorPane.topAnchor="45.0" />
                              <Label layoutX="10.0" layoutY="69.0" prefHeight="17.0" prefWidth="79.0" text="Размер диска:" AnchorPane.leftAnchor="10.0" />
                              <Label layoutX="97.0" layoutY="69.0" prefHeight="17.0" prefWidth="91.0" text="0 МБ" AnchorPane.leftAnchor="97.0" />
                              <Label layoutX="10.0" layoutY="93.0" text="Занято:" AnchorPane.leftAnchor="10.0" />
                              <Label layoutX="97.0" layoutY="93.0" prefHeight="17.0" prefWidth="93.0" text="0 МБ" AnchorPane.leftAnchor="97.0" />
                              <Label layoutX="10.0" layoutY="119.0" text="Свободно:" AnchorPane.leftAnchor="10.0" />
                              <Label layoutX="97.0" layoutY="119.0" prefHeight="17.0" prefWidth="92.0" text="0 МБ" />
                              <Label layoutX="10.0" layoutY="145.0" text="Выбрано файлов:" AnchorPane.leftAnchor="10.0" />
                              <Label layoutX="118.0" layoutY="145.0" prefHeight="17.0" prefWidth="71.0" text="0" AnchorPane.leftAnchor="115.0" />
                              <Label layoutX="10.0" layoutY="168.0" text="Архивировано:" AnchorPane.leftAnchor="10.0" />
                              <Label layoutX="118.0" layoutY="168.0" prefHeight="17.0" prefWidth="73.0" text="0" AnchorPane.leftAnchor="115.0" />
                              <Button layoutX="346.0" layoutY="330.0" mnemonicParsing="false" text="Запустить резервное копирование" AnchorPane.bottomAnchor="15.0" AnchorPane.rightAnchor="15.0" />
                              <ProgressBar layoutX="6.0" layoutY="333.0" prefHeight="18.0" prefWidth="174.0" progress="0.0" AnchorPane.bottomAnchor="18.0" AnchorPane.leftAnchor="5.0" AnchorPane.rightAnchor="233.0" />
                              <Label layoutX="13.0" layoutY="309.0" text="Выполнено:" AnchorPane.bottomAnchor="43.0" AnchorPane.leftAnchor="13.0" />
                              <Label layoutX="83.0" layoutY="309.0" prefHeight="17.0" prefWidth="54.0" text="0 %" AnchorPane.bottomAnchor="43.0" AnchorPane.leftAnchor="83.0" />
                           </children></AnchorPane>
                  </content>
                </Tab>
                <Tab text="Расписание">
                  <content>
                    <AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="180.0" prefWidth="200.0">
                           <children>
                              <RadioButton disable="true" layoutX="14.0" layoutY="45.0" mnemonicParsing="false" text="Ежечасно" AnchorPane.leftAnchor="14.0" />
                              <CheckBox layoutX="77.0" layoutY="14.0" mnemonicParsing="false" text="Использовать расписание для выбранного архива" AnchorPane.leftAnchor="77.0" AnchorPane.topAnchor="14.0" />
                              <RadioButton disable="true" layoutX="14.0" layoutY="81.0" mnemonicParsing="false" text="По дням" AnchorPane.leftAnchor="14.0" />
                              <CheckBox disable="true" layoutX="105.0" layoutY="81.0" mnemonicParsing="false" prefHeight="17.0" prefWidth="158.0" text="Понедельник" AnchorPane.leftAnchor="105.0" />
                              <CheckBox disable="true" layoutX="105.0" layoutY="109.0" mnemonicParsing="false" prefHeight="17.0" prefWidth="146.0" text="Вторник" AnchorPane.leftAnchor="105.0" />
                              <CheckBox disable="true" layoutX="105.0" layoutY="136.0" mnemonicParsing="false" prefHeight="17.0" prefWidth="134.0" text="Среда" AnchorPane.leftAnchor="105.0" />
                              <CheckBox disable="true" layoutX="105.0" layoutY="160.0" mnemonicParsing="false" prefHeight="17.0" prefWidth="134.0" text="Четверг" AnchorPane.leftAnchor="105.0" />
                              <CheckBox disable="true" layoutX="105.0" layoutY="185.0" mnemonicParsing="false" prefHeight="17.0" prefWidth="134.0" text="Пятница" AnchorPane.leftAnchor="105.0" />
                              <CheckBox disable="true" layoutX="105.0" layoutY="211.0" mnemonicParsing="false" prefHeight="17.0" prefWidth="144.0" text="Суббота" AnchorPane.leftAnchor="105.0" />
                              <CheckBox disable="true" layoutX="105.0" layoutY="241.0" mnemonicParsing="false" prefHeight="17.0" prefWidth="149.0" text="Воскресенье" AnchorPane.leftAnchor="105.0" />
                              <ComboBox disable="true" layoutX="103.0" layoutY="277.0" prefWidth="150.0" AnchorPane.leftAnchor="103.0" />
                           </children></AnchorPane>
                  </content>
                </Tab>
                  <Tab text="Восстановление">
                     <content>
                        <AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="180.0" prefWidth="200.0">
                           <children>
                              <Button layoutX="33.0" layoutY="46.0" mnemonicParsing="false" text="Выбрать архив" AnchorPane.leftAnchor="33.0" />
                              <Label layoutX="33.0" layoutY="83.0" prefHeight="17.0" prefWidth="365.0" text="Label" AnchorPane.leftAnchor="33.0" AnchorPane.rightAnchor="14.0" />
                              <RadioButton layoutX="14.0" layoutY="14.0" mnemonicParsing="false" selected="true" text="Восстановить всё" AnchorPane.leftAnchor="14.0" />
                              <Separator layoutX="14.0" layoutY="117.0" prefWidth="200.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" />
                              <RadioButton layoutX="14.0" layoutY="139.0" mnemonicParsing="false" text="Восстановить выбранные файлы и папки" />
                              <Button disable="true" layoutX="37.0" layoutY="172.0" mnemonicParsing="false" text="Выбрать файлы и папки" />
                              <Label layoutX="37.0" layoutY="210.0" text="Выбрано:" />
                              <Label layoutX="103.0" layoutY="210.0" text="0" />
                              <Separator layoutX="14.0" layoutY="248.0" prefWidth="200.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" />
                              <Button layoutX="338.0" layoutY="293.0" mnemonicParsing="false" text="Начать восстановление" AnchorPane.bottomAnchor="51.0" AnchorPane.rightAnchor="10.0" />
                              <ProgressBar layoutX="16.0" layoutY="297.0" prefHeight="18.0" prefWidth="223.0" progress="0.0" AnchorPane.bottomAnchor="54.0" AnchorPane.leftAnchor="14.0" AnchorPane.rightAnchor="175.0" />
                              <Label layoutX="19.0" layoutY="270.0" text="Выполнено:" AnchorPane.bottomAnchor="82.0" AnchorPane.leftAnchor="14.0" />
                              <Label layoutX="98.0" layoutY="270.0" text="0 %" AnchorPane.bottomAnchor="82.0" AnchorPane.leftAnchor="90.0" />
                           </children></AnchorPane>
                     </content>
                  </Tab>
                  <Tab text="Резервное копирование" />  
 
            СЮДА в коде надо подгрузить    backup.fxml
 
 
              </tabs>
            </TabPane>
         </children></AnchorPane>
  </items>
</SplitPane>
0
63 / 63 / 58
Регистрация: 19.01.2016
Сообщений: 152
29.05.2016, 21:18
Может так

XML
1
2
3
4
5
<Tab ....>
               <content>
                  <fx:include fx:id="backup" source="backup.fxml" />
               </content>
</Tab>
1
636 / 528 / 165
Регистрация: 01.04.2010
Сообщений: 1,843
30.05.2016, 08:49
Цитата Сообщение от kostrorod Посмотреть сообщение
Не до конца понял как подгрузить.
Получаешь ссылку на таб, в который надо загрузить контент, а потом по аналогии с моим примером грузишь контент из fxml в компоненту, и вызываешь у таба setContent(Node)

Цитата Сообщение от Николай Б Посмотреть сообщение
Может так
Можно и так, но тогда этот fxml будет загружаться при создании главной сцены, если это не принципиально, то так будет проще. В моём случае можно не загружать компоненту, например, до первого выбора таба.
1
39 / 28 / 8
Регистрация: 14.04.2012
Сообщений: 249
30.05.2016, 22:56  [ТС]
мне желательно подгружать после клика на таб

Как мне получить ссылку на tabPane из

Java
1
private SplitPane rootView;
он уже создан в этой панеле (SplitPane)

Добавлено через 31 минуту
Я нашёл как получить ссылку на компонент и подгрузить файл.

Java
1
2
3
4
 ObservableList<Node> list = rootView.getItems();
                AnchorPane anchorPane = (AnchorPane) list.get(1);
                TabPane tabPane = (TabPane) anchorPane.getChildren().get(0);
                tabPane.getTabs().get(3).setContent((Node) FXMLLoader.load(this.getClass().getResource("view/backup.fxml")));
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
inter-admin
Эксперт
29715 / 6470 / 2152
Регистрация: 06.03.2009
Сообщений: 28,500
Блог
30.05.2016, 22:56
Помогаю со студенческими работами здесь

Компонент, в который можно подгрузить HTML-код
Есть ли такой компонент, что-то типо Memo, но я туда мог подгрузить код HTML. К примеру, есть текст: Текст &lt;span...

Java FX+FXML
Есть двумерный массив в классе мейн int C = new int; C = 1; C = 1; C = 1; C = 1; C...

Окна + fxml
Создал программно меню программы. Обработчик кнопки: producer.setOnAction(new EventHandler&lt;ActionEvent&gt;() { ...

Не видит fxml
Создал view пытаюсь его загрузить , но выдает ошибку , пробывал по разному указать путь к fxml ,но никак не хочет ее видеть

Не видит FXML
Как видно из структуры проекта, нужный .fxml лежит во View. package Model (class Main) навсего его не видит.


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
6
Ответ Создать тему
Новые блоги и статьи
SDL3 для Web (WebAssembly): Реализация движения на Box2D v3 - трение и коллизии с повёрнутыми стенами
8Observer8 20.02.2026
Содержание блога Box2D позволяет легко создать главного героя, который не проходит сквозь стены и перемещается с заданным трением о препятствия, которые можно располагать под углом, как верхнее. . .
Конвертировать закладки radiotray-ng в m3u-плейлист
damix 19.02.2026
Это можно сделать скриптом для PowerShell. Использование . \СonvertRadiotrayToM3U. ps1 <path_to_bookmarks. json> Рядом с файлом bookmarks. json появится файл bookmarks. m3u с результатом. # Check if. . .
Семь CDC на одном интерфейсе: 5 U[S]ARTов, 1 CAN и 1 SSI
Eddy_Em 18.02.2026
Постепенно допиливаю свою "многоинтерфейсную плату". Выглядит вот так: https:/ / www. cyberforum. ru/ blog_attachment. php?attachmentid=11617&stc=1&d=1771445347 Основана на STM32F303RBT6. На борту пять. . .
Камера Toupcam IUA500KMA
Eddy_Em 12.02.2026
Т. к. у всяких "хикроботов" слишком уж мелкий пиксель, для подсмотра в ESPriF они вообще плохо годятся: уже 14 величину можно рассмотреть еле-еле лишь на экспозициях под 3 секунды (а то и больше),. . .
И ясному Солнцу
zbw 12.02.2026
И ясному Солнцу, и светлой Луне. В мире покоя нет и люди не могут жить в тишине. А жить им немного лет.
«Знание-Сила»
zbw 12.02.2026
«Знание-Сила» «Время-Деньги» «Деньги -Пуля»
SDL3 для Web (WebAssembly): Подключение Box2D v3, физика и отрисовка коллайдеров
8Observer8 12.02.2026
Содержание блога Box2D - это библиотека для 2D физики для анимаций и игр. С её помощью можно определять были ли коллизии между конкретными объектами и вызывать обработчики событий столкновения. . . .
SDL3 для Web (WebAssembly): Загрузка PNG с прозрачным фоном с помощью SDL_LoadPNG (без SDL3_image)
8Observer8 11.02.2026
Содержание блога Библиотека SDL3 содержит встроенные инструменты для базовой работы с изображениями - без использования библиотеки SDL3_image. Пошагово создадим проект для загрузки изображения. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru